要解决“遍历行以确定特定单词的计数”的问题,可以使用以下代码示例:
def count_word_occurrences(word, filepath):
count = 0
with open(filepath, 'r') as file:
for line in file:
words = line.strip().split(' ')
count += words.count(word)
return count
word = 'example'
filepath = 'textfile.txt'
occurrences = count_word_occurrences(word, filepath)
print(f"The word '{word}' occurs {occurrences} times in the file.")
这段代码定义了一个名为count_word_occurrences
的函数,它接受一个单词和一个文件路径作为参数。函数会打开指定路径的文件,并逐行遍历文件内容。对于每一行,它会将行拆分成单词列表,并计算目标单词在该列表中的出现次数。最后,函数返回目标单词的总出现次数。
在主代码中,我们指定了目标单词和文件路径,并调用count_word_occurrences
函数来获取目标单词在文件中的计数。然后,我们使用print
语句将结果输出到控制台。