[英]Sort a text file into a list determined by mode
我有一个文本文件:
hello my name is bill hello there hello there hiya hiya hiya
每个短语由四个空格分隔。 如何按频率对这些词进行排序(换行)。
任何帮助表示赞赏。
您可以为此使用collections.Counter
。
from collections import Counter
with open("your file.txt", "r") as f:
phrases = Counter(f.read().split(" "))
for phrase, occurrences in sorted(phrases.items(), key=lambda _: _[1], reverse=True):
print "Phrase: {} -- Occurrences: {}".format(phrase, occurrences)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.