-1

I made a program for fun to find the word 'love' in a sentence and list out how many 'love's there are. As you can see there are several requirements, the 'love' must be a word. That means it has to be separated by spaces or end in punctuation marks. I also account for 'love' starting at the start of the sentence.

num_loves = 0
inpt = input('type ')
for star in range(len(inpt) - 3):
if inpt[star] == 'l' or 'L' and inpt[star+1] == 'o' and inpt[star+2] == 'v' and inpt[star+3] == 'e':
    if inpt == 'love' or 'Love':
        num_loves = num_loves + 1
    elif star == 0 and inpt[star+4] == ' ' or '.' or ',' or '!' or '?':
        num_loves = num_loves + 1
    elif star != 0:
        if inpt[star-1] == ' ' and inpt[star+4] == ' ' or '.' or ',' or '!' or'?':
            num_loves = num_loves + 1
if num_loves != 0:
   print(num_loves)
print('true')
   if num_loves == 0:
print('false')

Although it's great at spotting 'love', it's too great. When I input 'Iloveyou' it still found the word love even though I don't want it to. This is exactly the reason why I input the code "inpt[star-1] == ' ' ". It seems like python ignored this part. Plz help. I'm using python 3.

AChampion
  • 29,683
  • 4
  • 59
  • 75
SCP001
  • 15
  • 2
  • does "Love Lovelive" count as 1 or 2? – Gareth Ma Aug 05 '18 at 02:46
  • 1
    Also you might want to use `str.count()` – Gareth Ma Aug 05 '18 at 02:46
  • This should also be tagged with [tag:python]. – user202729 Aug 05 '18 at 02:54
  • 2
    Python's `if` statements don't work the way you are expecting, look into using the `in` operator. Possible duplicate of [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – AChampion Aug 05 '18 at 03:15
  • You should use parenthesis in your complicated conditional statements. Even if you are certain of the precedence order, parenthesis help clarify your intent. – Bryan Oakley Aug 05 '18 at 03:41
  • Thank you guys so much! I just reviewed my code and I think I figured out a way to solve and simplify my problems. – SCP001 Aug 05 '18 at 12:10

1 Answers1

1

You have overcomplicated things and missed a few corner cases with the punctuation and things like that. There's much simpler solution:

from collections import Counter
inpt = input('type ')  # "Love Love lovelovelove Love love lovelove Love love love love"
no_punct = ''.join( [i.upper() if i.isalpha() else ' ' for i in inpt] )
print Counter(no_punct.split())['LOVE']

outputs:

8
lenik
  • 23,228
  • 4
  • 34
  • 43