繁体   English   中英

将文本文件排序到由模式确定的列表中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM