How to find the count of a word in a string?

后端 未结 9 777
北恋
北恋 2020-12-01 13:07

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

相关标签:
9条回答
  • 2020-12-01 13:29
    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.

    0 讨论(0)
  • 2020-12-01 13:30

    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
    
    0 讨论(0)
  • 2020-12-01 13:36

    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})
    
    0 讨论(0)
提交回复
热议问题