Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
拆分文件并将其转换为python中的字典_Python_Python 2.7_Dictionary_Split - Fatal编程技术网

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

拆分文件并将其转换为python中的字典,python,python-2.7,dictionary,split,Python,Python 2.7,Dictionary,Split,我想分割一个文件,然后想打印的话,这是使用最多的时间 但我甚至不能创建字典,上面的代码打印空字典{} 另外,我没有添加代码的第一部分,它用于打开文件、计算总行数以及以大写打印所有行 您可以使用collections.Counter(),它将文本作为输入,并返回一个记录文件中每个单词频率的字典 sample.txt: counts = dict() for word in x: # x is file named "f2.txt

我想分割一个文件,然后想打印的话,这是使用最多的时间

但我甚至不能创建字典,上面的代码打印空字典
{}



另外,我没有添加代码的第一部分,它用于打开文件、计算总行数以及以大写打印所有行

您可以使用
collections.Counter()
,它将文本作为输入,并返回一个记录文件中每个单词频率的字典

sample.txt:

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 
以及读取和记录单词频率的代码:

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

您必须使用
open
函数打开文件。@接下来,请参阅P.S.部分。我没有提到这一点,因为我认为这是不必要的。如果你愿意,我可以添加:)输入文件怎么样?@JoseRicardoBustosM。它是一个简单的
.txt
文件。我在守则中已提及这点。检查第二行注释。:)最好使用
集合的
计数器
,好的,谢谢。这一切我还没学会,但我能理解尽管我可以像往常一样看到反对票:(忽略那些反对票。继续练习,祝你好运
 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)]