I have a string \"Hello I am going to I with hello am
\". I want to find how many times a word occur in the string. Example hello occurs 2 time. I tried this app
from collections import *
import re
Counter(re.findall(r"[\w']+", text.lower()))
Using re.findall
is more versatile than split
, because otherwise you cannot take into account contractions such as "don't" and "I'll", etc.
Demo (using your example):
>>> countWords("Hello I am going to I with hello am")
Counter({'i': 2, 'am': 2, 'hello': 2, 'to': 1, 'going': 1, 'with': 1})
If you expect to be making many of these queries, this will only do O(N) work once, rather than O(N*#queries) work.
You can use the Python regex library re
to find all matches in the substring and return the array.
import re
input_string = "Hello I am going to I with Hello am"
print(len(re.findall('hello', input_string.lower())))
Prints:
2
Considering Hello
and hello
as same words, irrespective of their cases:
>>> from collections import Counter
>>> strs="Hello I am going to I with hello am"
>>> Counter(map(str.lower,strs.split()))
Counter({'i': 2, 'am': 2, 'hello': 2, 'to': 1, 'going': 1, 'with': 1})