来自txt文件的Python字数统计程序

时间:2015-10-28 06:52:46

标签: python python-3.5

我试图编写一个计算txt文件中最常见的5个单词的程序。

这是我到目前为止所做的:

file = open('alice.txt')
wordcount = {}

for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1

for k, v in wordcount.items():
    print (k, v)

该程序计算.txt文件中的每个单词。

我的问题是如何制作它所以它只计算文件中最常见的5个单词,以便它显示每个单词旁边的单词和单词计数。

一个问题 - 我无法使用字典......无论那意味着什么。

3 个答案:

答案 0 :(得分:1)

File_Name = 'file.txt'

counterDict = {}

with open(File_Name,'r') as fh:
    #Reading  all lines into a list.
    data = fh.readlines()

for line in data:
    # Removing some characters like '.' , ',' 
    # Changing all case into lower. 
    line = line.lower().replace(',','').replace('.','')
    # Splitting all words into list elements.
    words = line.split()
    for word in words:
        # Add the word into counterDict if  it is not present.
        # key should be 1.
        if word not in counterDict:
            counterDict[word] = 1
        #If the word is already in the counterDict, then increase its count by one.
        else:
            counterDict[word] = counterDict[word] + 1    

# The sorting will be based on word count.
# Eg : lambda x = (word,count) = x[0] = word , x[1]=count
sorted_counterDict = sorted(counterDict.items(), reverse=True , key=lambda x : x[1])

#sorted_counterDict[0:5] , print first five.
for key,val in sorted_counterDict[0:5]:
    print(key,val)

答案 1 :(得分:0)

有一个内置函数可以按键对字典进行排序:

sorted(wordcount, reverse=True)

现在由您决定如何获取/打印前五个元素;)

注意:当然 sorted 也可以对其他集合进行排序。

答案 2 :(得分:0)

很简单,您只需找到文件中最常见的5个单词

所以你可以这样做:

wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True)

然后,这个字典将按值排序(请记住sorted返回一个列表)。

您可以使用以下代码获取5个最常用的字词:

for k, v in wordcount[:5]):
    print (k, v)

所以完整的代码如下:

wordcount = {}

with open('alice.txt') as file:  # with can auto close the file
    for word in file.read().split():
        if word not in wordcount:
            wordcount[word] = 1
        else:
            wordcount[word] += 1

wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True)

for k, v in wordcount[:5]:
    print(k, v)

此外,这是一种更简单的方法,使用collections.Counter

from collections import Counter
with open('alice.txt') as file:  # with can auto close the file
    wordcount = Counter(file.read().split())

for k, v in wordcount.most_common(5):
    print(k, v)

输出与第一个解决方案相同。

相关问题