如何计算每个单词在txt文件中出现的次数?

时间:2015-09-28 14:24:06

标签: python

这是详细的作业: 编写一个完整的python程序,从一个名为trash.dat的文件中读取单词。假设文件中每行有一个单词。输出文件中每个不同单词(不区分大小写)的计数。例如,文件包含:

大鼠

输出:

狗= 2

猫= 1

大鼠= 1

3 个答案:

答案 0 :(得分:0)

你应该去做自己的功课来帮助你学习。但无论如何,这是一个解决方案。

#!/usr/bin/env python

dict = {}

with open("trash.dat", "rw") as f:
    for line in f:
        if line != "\n":
            if line.lower() in dict:
                dict[line.lower()] = dict[line.lower()] + 1
            else:
                dict[line.lower()] = 1

for x in dict:
    print "%s=" % x, dict[x]

答案 1 :(得分:0)

#!python2

from collections import Counter

words = []

# load words to list
with open('trash.dat', 'r') as fp:
    for line in fp:
        if line != '\n':
            words.append(line.lower().rstrip())

# make a dictionary from the 'words' list
cnt = Counter(words)

# print out the key, value pairs
for k, v in cnt.items():
    print 'the count of ' + k + ' is: ' + str(v)

'''
# output
the count of rat is: 1
the count of dog is: 2
the count of cat is: 1
''''

答案 2 :(得分:0)

这可能会有所帮助:

theWords = []
with open('fileName.dat', 'r') as file:
for every line in file:
    theWords.append(line.lower().rstrip("\n"))

print("Rat = " + theWords[1])
print("Dog = " + theWords[2])
print("Cat = " + theWords[3])

文件中的每一行都将被分隔。