[英]Storing the count of each word occurring in a text file
我想將出現在字典中的文本文件中每個單詞的計數存儲起來。 我的意思是
fob= open('D:/project/report.txt','r')
我能夠將這些行存儲到一個列表中,但是我需要將這些行拆分成單個單詞,最后存儲它們的計數(就像在字典中一樣)。
lst=fob.radlines()
#This doesn't work, gives error
#AttributeError: 'list' object has no attribute 'split'
mylst=lst.split()
我怎樣才能做到這一點 ? 而有效的方法是什么呢?
對於Python 2.7+
from collections import Counter
with open('D:/project/report.txt','r') as fob:
c = Counter(word for line in fob for word in line.split())
對於Python 2.5+
from collections import defaultdict
dd = defaultdict(int)
with open('D:/project/report.txt','r') as fob:
for line in fob:
for word in line.split():
dd[word] += 1
對於較老的python或討厭defaultdict
d = {}
with open('D:/project/report.txt','r') as fob:
for line in fob:
for word in line.split():
d[word] = d.get(word, 0) + 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.