0

I want to find if some spam words like "gift", "sign" and "buy" are in my text, and I know gift and sign appear twice and one time respectively, but when I run the below code the count is 0 for all words. Any help?

efile= open('email.txt', 'r')
eMail = efile.read()

gift_count = 0
sign_count = 0
buy_count = 0

for word in eMail:
    if word == 'sign':
        sign_count+=1
    if word == 'gift':
         gift_count+=1
    if word == 'Buy':
        buy_count += 1
         
efile.close()

print (" In the email file: the words  sign appears " \
       , sign_count," the word gift appears " \
      , gift_count, " the word Buy appears " \
      , buy_count)
Phix
  • 9,364
  • 4
  • 35
  • 62
datagalz
  • 47
  • 4
  • See [how to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – jarmod Nov 16 '20 at 23:30
  • what is the content of `email.txt`? – Ali Tou Nov 16 '20 at 23:30
  • Are you, perhaps, expecting `for word in eMail:` to break the text apart into words, simply because you used the name `word`? – Karl Knechtel Nov 16 '20 at 23:31
  • I wanted to unswer but ..... you can use Count from the built-in lib collection ``` from collections import Counter efile= open('email.txt', 'r') eMail = efile.read() count_words=Counter(eMail.lower().split()) print(count_words['sign']) print(count_words.most_commun(5)) ``` – Simone Nov 16 '20 at 23:38

1 Answers1

2

when you iterate over read() result you are iterating letter after letter, not word after word. To fix that use words = file.read().split(" ")

Tamir
  • 1,224
  • 1
  • 5
  • 18