简体   繁体   中英

The number of repetitions of a word in a txt file in Python

I want count The number of repetitions of a word in a txt in Python This is my code

    f=open('D:/hi.txt','r')
    f.read()
    h=input('enter a word:')
    def file()
        if h in f:
            Print(f.count)
with open('D:/hi.txt','r') as f:
    content = f.read()

h = input('enter a word:')

words = content.lower().split()

print(words.count(h))

Explanation: this reads the file D:/hi.txt into a string content , then separates the words into a list words (assuming you do not care about capitalization here) and then simply counts how often the inputted word h occurs in words .

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