- 1
take a word as input and output the number of times that word appears in the quote.
i did this but its not working please tell me how to do it.... import re quote = "Always do your best. Your best is going to change from moment to moment; it will be different when you are healthy as opposed to sick. Under any circumstance, simply do your best, and you will avoid self-judgment, self-abuse and regret" word = input() pattern=r”word" print(len(re.findall(pattern,word)))
10 Respostas
+ 2
check my previous (corrected) answer...
but you could also just use:
pattern = r"\b"+word+r"\b"
+ 1
with your pattern, you just search all the word "word" found in... word ^^
you should search inside quote, the value of word...
if you are quite sure input cannot have regex special meaning chars, you can do:
word = input()
pattern = re.compile(r"\b"+word+r"\b")
print(len(re.findall(pattern,quote)))
Rahul Prasad edit:
\b stand for boundary (not word char before/after)
little correction of compile argument ^^
+ 1
r is not related to regular expression, but to raw string (meaning that python does not interpret escaped character such as "\n")... needed to preserve anti-slash without having to escape them ("\\")... it's usefull when you want to escape anti-slash indide reg exp pattern (r"\\" vs "\\\\").
to search value of word as a reg exp pattern, you must escape characters wich have special meanings in reg exp... assuming you search only for basic words, you could just use you word string... but you will match 'car' in 'carpet' (as example), so to search for full words, you need to append and prepend r"\b" (word boundary) to your word string ;)
0
visph
word = input()
pattern = r"word"
print(len(re.findall(pattern,quote)))
actually i am unable to understand what should i write in patter since word is in input form
to tell me what syntax is used for that
0
visph yes but what is the syntax to search value of word inside r" "
0
???
0
visph pattern =r"what will i write here"
0
visph can you explain about this one i did not know about this syntax ...
pattern = r"\b"+word+r"\b"
0
visph Thanks for your help
0
did you have successed the lesson code coach?