我的代码需要帮助。我正在尝试定义一个函数,该函数将在文本文件中搜索特定的单词,然后打印出所有带有给定单词的行以及该单词出现在文本文件中的总次数。
int add2nums( int, int);
输出需要显示单词和总数。 例如:文本文件中包含OG的单词。
需要正确的输出:
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)
答案 0 :(得分:0)
尝试一下。
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')