Search code examples
pythoncomputer-science

How to count words in a file using python >2.0


I want to write a program that can count keywords in a file. Example: I created a list, with the following keywords. Then I open a file with bunch of words, and I want to count how many keywords are there in the file. But no matter what I do, the count will always give me 0. What did I do wrong?

Here is my code:

Happy = ['amazed', 'amazing', 'best', 'excellent', 'excited', 'excite', 
         'excites', 'exciting', 'glad', 'greatest', 'happy', 'love',
         'loves', 'loved', 'loving', 'lovin', 'prettiest']

def CountFile():
  file = open("File.txt", "r")
  Count = 0
  for i in file:
    i = i.split()
    if i in Happy:
      count = count + 1
  print("there are" count "keywords")
  return

CountFile()

Solution

  • Try this code

    Happy = ['amazed', 'amazing', 'best', 'excellent', 'excited', 'excite', 'excites', 'exciting', 'glad', 'greatest', 'happy', 'love', 'loves', 'loved', 'loving', 'lovin', 'prettiest']

    def CountFile():
       file = open("File.txt", "r")
       count = 0
       for i in file:
          i = i.split()
          for so in i:
             if so in Happy:  
                count = count + 1
       print("there are %s keywords" %count)
    
    CountFile()