[英]define a function to search for a specific word in a text file and print total lines
I need help with my code. 我的代码需要帮助。 I am trying to define a function that will search for a specific word in a text file and then print out all the lines with the give word and the total of times the word appears in the text file.
我正在尝试定义一个函数,该函数将搜索文本文件中的特定单词,然后打印出包含给定单词的所有行以及单词出现在文本文件中的总次数。
def read_words(fname):
fin = open(fname)
es_count = 0
for w in fin:
word=w
if " " in word:
es_count = es_count + 1
print(word)
The output needs to show the words and the total count. 输出需要显示单词和总计数。 For example: words in text file that have OG in them.
例如:文本文件中包含OG的单词。
correct output needed: 正确的输出需要:
dog
fog
jog
hog
the total number of words: 4
Try this. 尝试这个。
def read_word(fname, word):
fin = open(fname)
founds = []
for line in fin.readlines():
if word in line:
founds.append(line)
print('\n'.join(founds))
print('the total number of words: %d' % len(founds))
read_word(fname='file.txt', word='og')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.