【问题标题】:Count number of sentences which contains words from other list Python [closed]计算包含来自其他列表Python的单词的句子数[关闭]
【发布时间】:2020-05-16 04:24:56
【问题描述】:

我有两个列表,我正在尝试查找另一个列表中包含的一个列表中的字数

样本数据

list1 = ['apple','orange','ball','peach']
df['list2'] = ['Apples were served as the dessert','They like apples','I prefer oranges to apples.','Tom drank his orange juice','These oranges have gone bad','He could hit the ball, too']

我的输出应该是

apples 2
oranges 3
ball 1

我可以通过提取每个字符串来计数,但我的 list1 有 60 多个单词。如果它包含在list2中,是否可以获得所有单词的计数?提前致谢

我的代码

df = df[df.list2.str.lower().str.contains('apples')]

【问题讨论】:

  • “我的代码”不是有效的 Python。
  • @ScottHunter - 这是有效的熊猫代码
  • @jezrael 至少需要在问题中提及熊猫。
  • 这个也需要模糊匹配

标签: python pandas list count


【解决方案1】:

就个人而言,我会从第一个列表中制作一本字典

dictOfWords = { i : 5 for i in listOfStr }

dictOfWords 现在看起来像这样

{'apple': 0, 'orange': 0, 'ball': 0, 'peach': 0}

然后您可以使用嵌套的 for 循环遍历您的短语列表

for key in dictOfWords:
  for element in list:
    if key in element:
      dictOfWords[element]+=1

【讨论】:

    【解决方案2】:

    如果可能的话,通过子字符串的计数来简化问题,例如 pineapples 是计数,例如 apple 解决方案是:

    from collections import Counter
    
    list1 = ['apple','orange','ball','peach']
    
    a = Counter([y for x in df['list2'] for y in list1 if y in x.lower()])
    print (a)
    Counter({'apple': 3, 'orange': 3, 'ball': 1})
    
    df1 = pd.DataFrame({'vals': list(a.keys()), 'count': list(a.values())})
    print (df1)
         vals  count
    0   apple      3
    1  orange      3
    2    ball      1
    

    【讨论】:

    • 把其中一个苹果换成菠萝
    【解决方案3】:

    使用Series.str.extractall 和Series.value_counts:

    df['list2'].str.extractall(f"({'|'.join(list1)})")[0].value_counts()
    
    orange    3
    apple     2
    ball      1
    Name: 0, dtype: int64
    

    注意:正如 cmets 中提到的,str.extractall 的“灵活性”是有代价的,它可以匹配其中包含“apples”的任何字符串。因此,例如“菠萝”也会被计算在内。

    【讨论】:

    • 一样~把其中一个苹果换成菠萝,用空格提取,会有帮助~
    • 查看编辑@YOBEN_S(ps,再次更改名称:)?)
    • 名字里有空格,别人很难@我~马上删空格~
    • 谢谢你,效果很好。我需要一个相对匹配而不是绝对匹配,所以代码效果很好。
    【解决方案4】:

    不确定您的 df['list2'] 指的是什么,但这里有一个工作示例:

    list1 = ['apple','orange','ball','peach']
    list2 = [
        'Apples were served as the dessert',
        'They like apples','I prefer oranges to apples.',
        'Tom drank his orange juice',
        'These oranges have gone bad',
        'He could hit the ball, too'
    ]
    # Creating a dictionary of words from list1
    word_dict = {w : 0 for w in list1}
    
    # Looping through each word of list1
    for w in list1:
        # Looping through each sentence of list2
        for s in list2:
            if w in p:
                # If the word of list 1 is present in the sentence of list2, add 1 to the count
                word_dict[w] += 1
    print(word_dict)
    

    希望这会有所帮助!

    【讨论】:

    • 效果很好。谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    相关资源
    最近更新 更多