我是python的新手。我得到了一个文件夹,里面有大约2000个文本文件。我应该输出每个单词和它出现的次数(在文件中没有重复)。例如,句子"i am what I a“必须在一个文件中只包含一次出现的"i”。
我可以对单个文件执行此操作,但如何对多个文件执行此操作?
from collections import Counter
import re
def openfile(filename):
fh = open(filename, "r+")
str = fh.read()
fh.close()
return str
def removegarbage(str):
# Replace one or more non-word (non-alphanumeric) chars with a space
str = re.sub(r'\W+', ' ', str)
str = str.lower()
return str
def getwordbins(words):
cnt = Counter()
for word in words:
cnt[word] += 1
return cnt
def main(filename, topwords):
txt = openfile(filename)
txt = removegarbage(txt)
words = txt.split(' ')
bins = getwordbins(words)
for key, value in bins.most_common(topwords):
print key,value
main('speech.txt', 500)
发布于 2013-06-08 10:06:29
您可以通过在glob
模块中使用glob()
或iglob()
函数来获取文件列表。我注意到您没有有效地使用Counter
对象。只调用它的update()
方法并将单词列表传递给它会更好。下面是代码的简化版本,它处理指定文件夹中的所有*.txt
文件:
from collections import Counter
from glob import iglob
import re
import os
def remove_garbage(text):
"""Replace non-word (non-alphanumeric) chars in text with spaces,
then convert and return a lowercase version of the result.
"""
text = re.sub(r'\W+', ' ', text)
text = text.lower()
return text
topwords = 100
folderpath = 'path/to/directory'
counter = Counter()
for filepath in iglob(os.path.join(folderpath, '*.txt')):
with open(filepath) as file:
counter.update(remove_garbage(file.read()).split())
for word, count in counter.most_common(topwords):
print('{}: {}'.format(count, word))
发布于 2013-06-08 07:33:07
查看os.listdir()
,它会给你一个目录中所有条目的列表。
发布于 2013-06-08 07:49:45
如果我没有记错的话,您需要计算每个单词包含此单词的文件数。这是你可以做的。
对于每个文件,获取该文件中的一组单词(即单词应该是唯一的)。然后,对于每个单词计数它可以在其中找到的集合的数量。
以下是我的建议:
os.listdir
实现此目的。with open(filepath,'r') as f: txt = removegarbage(f.read()) words = set(txt.split())
Counter
了。最好使用它的update
方法。这里有一个小的demo:a = set("hello Python world hello".split()) >>> a {'Python','world',' hello '} >>> b= set("foobar hello world".split()) >>> b {'foobar','hello','world'} >>> c=demo:a() >>> c.update(a) >>> c.update(b) >>> c Counter({'world':2,'hello':2,'Python':1,‘'foobar':1})https://stackoverflow.com/questions/16997165
复制相似问题