简体   繁体   中英

Using a Text file to count certain words in PYTHON

I am in need of a lot of help. I am trying to use a text file to count only certain words from the text. I have been searching for hours to try and find help, but cant seem to find any.

NEEDS TO BE incase senitive The words i need to use are: great, good, perfect, nice, fantastic, loved, love, happy, enjoyed, fabulous

You can use regular expressions like "re.findall" or "re.finditer" expressions to search the words, then loop through whole file.

    list = []
    with open("file.txt") as f:
        words = f.read()
        list.append(re.findall(r"great", words))

Then you can count the words through len function. The code might need minor modifications according to the requirements. Go through the regular expressions page for more info on it.

You can even use str.count().

collections.Counter offers many options for counting words

from collections import Counter

with open('alice.txt') as f:
    content = f.read()

c = Counter(content.split())

print(c['you'])

lst = ['me', 'them', 'us']

for i in lst:
    print(f'{i}: {c[i]}')

for word, count in c.most_common(5):
    print(word + ':', count)
 301 me: 46 them: 49 us: 10 the: 1664 and: 780 to: 773 a: 662 of: 596

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