简体   繁体   中英

Counting occurrences of word in a text file

我必须编写一个程序来要求计算机上的特定文件名,计算文件中的字符和单词数,最后,该程序应该能够计算单词的数量(来自用户输入)。

You are finishing iterating over the file before you are attempting to count the occurrence of a specific word. Reorganizing your code to put all of the counting in the file iterations should fix it.

numLines = 0 
numWords = 0
numChars = 0
count = 0

filename = input("Which file would you like to work with?: ")
freq_word = input("Which word would you like to find the frequency for?: ")

with open(filename, 'r') as fin:
    for line in fin: 
        words = line.split()
        for word in words:
            if word == freq_word:
                count +=1

        numWords += len(words)
        numChars += len(line)

print(filename, "contains: ", numChars, "characters and total amount of words is: ", numWords)
print(freq_word, "occurs ", count, "number of time")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM