拆分文件并将其转换为 python 中的字典

Split file and turn it into dictionary in python

counts = dict()

for word in x:                                  # x is file named "f2.txt"
    words = word.split()
    print words
    counts[words] = counts.get(words,0) + 1
print counts 

我想拆分一个文件,然后打印使用次数最多的单词。

但我什至无法创建字典,上面的代码打印出空字典 {}


P.S。我没有添加代码的第一部分,它用于打开文件、计算总行数和以大写形式打印所有行。

您可以使用 collections.Counter() 将文本作为输入,returns 字典记录文件中每个单词的出现频率。

sample.txt:

hello this file is good
file is is good excellent

以及读取并记录词频的代码:

import collections
with open("sample.txt", "r") as datafile:
    lines = datafile.read()
    words = lines.split()
    words_hist = collections.Counter(words)
    print words_hist

输出:

{'is': 3, 'good': 2, 'file': 2, 'this': 1, 'excellent': 1, 'hello': 1}

根据您发布的解决方案,您似乎错误地读取了输入文件。所以我稍微修改了你的方法:

counts = dict()

with open("sample.txt", "r") as datafile:
    x = datafile.read().split()
    for word in x:                               
        words = word.split()
        print words
        counts[word] = counts.get(word,0) + 1
print counts

你问的是最常见的word.I已经显示了三个最常见的词。

 In [102]: line
    Out[102]: ' Mom   can   I    have  an  ice cream?Mom I Mom Mom'

    In [103]: li=line.split()

    In [104]: li
    Out[104]: ['Mom', 'can', 'I', 'have', 'an', 'ice', 'cream?Mom', 'I', 'Mom', 'Mom']

    In [105]: collections.Counter(li)
    Out[105]: Counter({'Mom': 3, 'I': 2, 'ice': 1, 'an': 1, 'can': 1, 'have': 1, 'cream?Mom': 1})

    In [106]: collections.Counter(li).most_common(3)
    Out[106]: [('Mom', 3), ('I', 2), ('ice', 1)]