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()
yacc
  • 2,915
  • 4
  • 19
  • 33
Qwert
  • 67
  • 6

2 Answers2

2

When you do i = i.split()

i becomes a list. Your i variable is a line in your text file here.

You can probably do,

   ...
   words = i.split()
   for w in words:     
     if w in Happy:
       count += 1
   ...
dgumo
  • 1,838
  • 1
  • 14
  • 18
2

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()
sachin dubey
  • 755
  • 9
  • 28