【问题标题】:How do I count the occurrence of each item from a list in a string in Python?如何计算Python中字符串列表中每个项目的出现次数?
【发布时间】:2019-09-26 04:21:48
【问题描述】:

假设我有以下列表。

food_list = ['ice cream', 'apple', 'pancake', 'sushi']

我想在以下字符串中找到该列表中的每个项目。

my_str = 'I had pancake for breakfast this morning, while my sister ate some apples. I brought one apple and ate it on my way to work. My coworker was having his birthday today, and he gave us free ice cream. It was the best ice cream I had this year.'

my_str = my_str.lower()

我要统计字符串中的项数。

ice cream : 2, apple: 1, pancake: 1, sushi:0

注意苹果只计算一次,因为apples 不应该被计算在内。由于ice cream 之类的项目,我不可能将其按空间拆分。

我正在考虑用一些东西替换列表中的单词并稍后计算,但它非常慢(当应用于更大的数据时)。我想知道是否有更好的解决方案。

for word in food_list:
    find_word = re.sub(r'\b'+word+r'\b', "***", my_str)
    count_word = find_word.count("***")
    print(word+": "+str(count_word))

我希望它足够清楚。谢谢

【问题讨论】:

    标签: python arrays string list


    【解决方案1】:

    re.findall 与字典理解一起使用:

    import re
    
    cnt = {k: len(re.findall(r'\b{}\b'.format(k), my_str)) for k in food_list}
    

    输出:

    {'apple': 1, 'ice cream': 2, 'pancake': 1, 'sushi': 0}
    

    【讨论】:

    • 我感谢所有其他回复。但是我最喜欢这个,因为我可以立即理解它,并且是我最终使用的那个。谢谢大家。
    【解决方案2】:

    您可以使用 re.finditer 匹配字符串中的确切单词

    import re
    
    
    food_list = ['ice cream', 'apple', 'pancake', 'sushi']
    
    my_str = 'I had pancake for breakfast this morning, while my sister ate some apples. I brought one apple and ate it on my way to work. My coworker was having his birthday today, and he gave us free ice cream. It was the best ice cream I had this year.'
    my_str = my_str.lower()
    
    
    output = {}
    for word in food_list:
       count = sum(1 for _ in re.finditer(r'\b%s\b' % re.escape(word), my_str))
       output[word] = count
    

    输出:

    for word, count in output.items():
        print(word, count)
    
    >>> ice cream 2
    >>> apple 1
    >>> pancake 1
    >>> sushi 0
    

    【讨论】:

    • 有趣。从未听说过re.finditer。但是,即使您已经使用了它,您仍然必须使用 \b 的东西吗?
    • @AnnaRG acctaully re.finditer 只返回一个产生 MatchObject 实例的迭代器,但我们必须使用 \b 来匹配字符串中的精确模式或单词。
    【解决方案3】:

    您可以简单地使用在字典理解中考虑单词边界的正则表达式:

    >>> import re
    >>> {food: sum(1 for match in re.finditer(r"\b{}\b".format(food), my_str)) for food in food_list}
    {'pancake': 1, 'sushi': 0, 'apple': 1, 'ice cream': 2}
    

    【讨论】:

      【解决方案4】:

      在单次扫描中,正则表达式将尝试查找所有匹配项,然后可以根据字符串中找到的所有匹配项计算每个匹配项的计数。

      food_list = ['ice cream', 'apple', 'pancake', 'sushi']
      regex = '|'.join([r'\b'+ item + r'\b' for item in food_list])
      my_str = 'I had pancake for breakfast this morning, while my sister ate some apples. I brought one apple and ate it on my way to work. My coworker was having his birthday today, and he gave us free ice cream. It was the best ice cream I had this year.'
      my_str = my_str.lower()
      all_matches = re.findall(r'%s' % regex, my_str)
      count_dict = {item: all_matches.count(item) for item in food_list}
      

      【讨论】:

        【解决方案5】:

        你可以通过调整起始位置来遍历字符串查找匹配:

        def find_all(a_str, sub):
        start = 0
        counter = 0
        while True:
            start = a_str.find(sub, start)
            if start == -1: return
            counter += 1
            yield start
            start += len(sub) # use start += 1 to find overlapping matches
        
        if __name__ == "__main__":
            food_list = ['ice cream', 'apple', 'pancake', 'sushi']
            my_str = 'I had pancake for breakfast this morning, while my sister ate some apples. I brought one apple and ate it on my way to work. My coworker was having his birthday today, and he gave us free ice cream. It was the best ice cream I had this year.'
            my_str = my_str.lower()
            counts = {}
            for item in food_list:
                counts.update({item: len(list(find_all(my_str, item)))})
            print(counts)
        

        【讨论】:

          猜你喜欢
          • 2014-08-22
          • 1970-01-01
          • 2022-12-04
          • 1970-01-01
          • 2022-07-27
          • 2022-10-15
          • 2019-10-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多