定义一个函数来搜索文本文件中的特定单词并打印总行

时间:2019-05-04 15:38:32

标签: python python-3.7

我的代码需要帮助。我正在尝试定义一个函数,该函数将在文本文件中搜索特定的单词,然后打印出所有带有给定单词的行以及该单词出现在文本文件中的总次数。

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)

1 个答案:

答案 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')