简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM