Reputation: 45
I am writing a code, to count the frequency of word occurrences in a document containing about 20,000 files,i am able to get the overall frequency of a word in the document and my code so far is:
import os
import re
import sys
sys.stdout=open('f2.txt','w')
from collections import Counter
from glob import iglob
def removegarbage(text):
text=re.sub(r'\W+',' ',text)
text=text.lower()
return text
folderpath='d:/articles-words'
counter=Counter()
d=0
for filepath in iglob(os.path.join(folderpath,'*.txt')):
with open(filepath,'r') as filehandle:
d+=1
r=round(d*0.1)
for filepath in iglob(os.path.join(folderpath,'*.txt')):
with open(filepath,'r') as filehandle:
words=set(removegarbage(filehandle.read()).split())
if r > counter:
counter.update()
for word,count in counter.most_common():
print('{} {}'.format(word,count))
But, I want to modify my counter, and update it only when the count is greater than r=0.1*(no of files) in short, i want to read words whose frequency in the entire document is greater than 10% of the number of documents. the error is:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
TypeError: unorderable types: int() > Counter()
how do I modify it?
Upvotes: 2
Views: 2107
Reputation: 8945
How about somethiing like this?
from glob import glob # (instead of iglob)
...
filepaths = glob(os.path.join(folderpath,'*.txt'))
num_files = len(filepaths)
# Add all words to counter
for filepath in filepaths):
with open(filepath,'r') as filehandle:
lines = filehandle.read()
words = removegarbage(lines).split()
counter.update(words)
# Display most common
for word, count in counter.most_common():
# Break out if the frequency is less than 0.1 * the number of files
if count < 0.1*num_files:
break
print('{} {}'.format(word,count))
Use of Counter.iteritems()
:
>>> from collections import Counter
>>> c = Counter()
>>> c.update(['test', 'test', 'test2'])
>>> c.iteritems()
<dictionary-itemiterator object at 0x012F4750>
>>> for word, count in c.iteritems():
... print word, count
...
test 2
test2 1
Upvotes: 2