I'm not exactly sure what's going on here. The result is 0. I'm trying to find the occurrence of a word in a list.
def count(sequence,item):
total=0 #counter
if type(sequence)==list or dict: #the if works for a list or list of lists
for element in sequence:
if element ==item:
total =1
else: #the else works for strings, where item is a word
sequence=sequence.replace(',','') #remove commas
sequence=sequence.replace('.','') #remove periods
sequence=sequence.lower() #make lowercase
for word in sequence.split(): #will iterate through words instead of characters
if word==item:
total =1
return total
print (count(["Hello how are you today.","today you are"], "you"))
CodePudding user response:
As mentioned in my comment, if type(sequence)==list or dict
will always evaluate to true since dict
is truthy. I think what you're looking for here is if type(sequence) == list or type(sequence) == dict
All that being said you can just use the built in function count
like so:
x = ["Hello how are you today.","today you are"]
search_word = 'you'
total = 0
for i in x:
total = i.split().count(search_word)
print(f'Got tota: {total}')
CodePudding user response:
def wordInSentence(searchWord, sentence):
sentence=sentence.replace(',','') #remove commas
sentence=sentence.replace('.','') #remove periods
sentence=sentence.lower() #make lowercase
for word in sentence.split(): #will iterate through words instead of characters
if word==searchWord:
def count(sequence,item):
total=0 #counter
if type(sequence)==list or type(sequence)==dict: #the if works for a list or list of lists
for element in sequence:
if wordInSentence(element, item):
total =1
else: #the else works for strings, where item is a word
if (wordInSentence(sequence, item):
total =1
return total
print (count(["Hello how are you today.","today you are"], "you"))