您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-在文本文件中查找单词列表的单词频率

Python-在文本文件中查找单词列表的单词频率

如果我了解您的问题,collections.Counter()可以解决此问题。

文档中的示例似乎可以解决您的问题。

# Tally occurrences of words in a list
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    cnt[word] += 1
print cnt


# Find the ten most common words in Hamlet
import re
words = re.findall('\w+', open('hamlet.txt').read().lower())
Counter(words).most_common(10)

从上面的示例中,您应该能够:

import re
import collections
words = re.findall('\w+', open('1976.03.txt').read().lower())
print collections.Counter(words)

幼稚的方法显示一种方式。

wanted = "fish chips steak"
cnt = Counter()
words = re.findall('\w+', open('1976.03.txt').read().lower())
for word in words:
    if word in wanted:
        cnt[word] += 1
print cnt
python 2022/1/1 18:32:32 有211人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶