[英]How can I count the number of times each word appears in a txt file?
Here is the assignment in detail: Write a complete python program which reads words from a file called trash.dat.下面是详细的作业: 编写一个完整的 Python 程序,它从名为trash.dat 的文件中读取单词。 Assume there is one word per line in the file.
假设文件中每行有一个单词。 Output the count for each of the different words (case insensitive) in the file.
输出文件中每个不同单词(不区分大小写)的计数。 For example a file with:
例如一个文件:
dog
Dog
cat
rat
Would output:会输出:
dog=2
cat=1
rat=1
You should go off and do your own homework to help you learn.你应该出去做自己的功课来帮助你学习。 But regardless, here is a solution.
但无论如何,这里有一个解决方案。
#!/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]
#!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
''''
This might help:这可能有帮助:
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])
Every line in your file will be seperated.文件中的每一行都将被分隔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.