简体   繁体   English

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

[英]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.

相关问题 如何计算一个单词出现在 csv 文件的每一行中的次数,在 python 中 - How to count the number of times a word appears in each row of a csv file, in python 计算每个成绩在文件中出现的次数 - Count Number of times each grade appears in a file 如何计算键的每个值出现的次数? - How do I count the number of times each value appears for a key? 如何找出一个字符串出现在txt文件中的次数? - How can I find out the number of times a string appears in a txt file? 使用字典计算每个字母在单词中出现的次数 - count the number of times each alphabet appears in a word using dictionary 我正在尝试使用Python3计算一个单词出现在.txt文件中的时间 - I am trying to count the number of time a word appears in a .txt file using Python3 如何计算每个单词在以下出现的次数 - How can I produce a count on the number of times each word has occurred in the following 如何计算一个数字出现在文件中每个数字开头的次数? (蟒蛇) - How to count the number of times a digit appears at the beginning of each number in a file? (python) 如何计算一个单词序列在文件中出现的次数,使用Python中的MapReduce? - How to count the number of times a word sequence appears in a file, using MapReduce in Python? 如何使用python计算字母在单词中出现的次数 - How count the number of times a letter appears in word using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM