take a word as input and output the number of times that word appears in the quote. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 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)))

26th Feb 2021, 12:45 AM
Rahul Prasad
Rahul Prasad - avatar
10 Answers
+ 2
check my previous (corrected) answer... but you could also just use: pattern = r"\b"+word+r"\b"
26th Feb 2021, 1:21 AM
visph
visph - avatar
+ 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 ^^
26th Feb 2021, 12:53 AM
visph
visph - avatar
+ 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 ;)
26th Feb 2021, 1:48 AM
visph
visph - avatar
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
26th Feb 2021, 1:16 AM
Rahul Prasad
Rahul Prasad - avatar
0
visph yes but what is the syntax to search value of word inside r" "
26th Feb 2021, 1:24 AM
Rahul Prasad
Rahul Prasad - avatar
0
???
26th Feb 2021, 1:25 AM
visph
visph - avatar
0
visph pattern =r"what will i write here"
26th Feb 2021, 1:30 AM
Rahul Prasad
Rahul Prasad - avatar
0
visph can you explain about this one i did not know about this syntax ... pattern = r"\b"+word+r"\b"
26th Feb 2021, 1:40 AM
Rahul Prasad
Rahul Prasad - avatar
0
visph Thanks for your help
26th Feb 2021, 3:05 AM
Rahul Prasad
Rahul Prasad - avatar
0
did you have successed the lesson code coach?
26th Feb 2021, 3:06 AM
visph
visph - avatar