[英]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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.