-2

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

  • 2
    Sorry but we cannot help you unless you show what you have tried. Look for tutorials on how to read from text file. How to iterate through the data you read and how to compare the iterations to your list of words (there is a specific method to enforce case-sensitivity, and increment your counters if there is a match. Good luck – Wazaki Oct 19 '18 at 23:51
  • 1
    Possibly helpful or related [Python - Finding word frequencies of list of words in text file](https://stackoverflow.com/questions/14921436/python-finding-word-frequencies-of-list-of-words-in-text-file) – chickity china chinese chicken Oct 19 '18 at 23:54

2 Answers2

0

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().

Vihasith
  • 31
  • 6
0

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
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20