【问题标题】:Iterating through a list of names to find specific keyword遍历名称列表以查找特定关键字
【发布时间】:2020-08-21 22:11:30
【问题描述】:

所以对于这个问题。我有这个专栏:

Column of product names 我需要创建一个函数,它接受一个关键字并返回名称中包含该单词的所有产品。对于这个特定的问题,关键字是“小麦”。我的功能如下:

def find_word(keyword):
    word = []
    for i in range(len(df)):
        if keyword in df['name'][i]:
            word.append(df['name'][i])
    return word
find_word("Wheat")

这就是返回的内容:

['小麦奶油(快速)', “脆皮小麦和葡萄干”, '磨砂迷你小麦', '营养谷物小麦', '膨化小麦', '碎小麦', “碎麦麸”, '碎小麦勺子大小', '草莓水果小麦', '小麦检验', '小麦', 'Wheaties Honey Gold']

如您所见,最后 2 个以及倒数第 3 个不属于。我不确定如何构造函数来查找这些情况。

【问题讨论】:

  • 为什么最后 3 个不属于?他们都有“小麦”。
  • 您是否希望仅在“小麦”本身是一个词时进行匹配?另外我不知道上下文,但似乎最好将您的数据框作为参数传递给函数,以使您的函数更加通用。
  • 在你的函数中提供“小麦”,如:find_word("小麦"),注意小麦后面的使用空间
  • @Samwise 他们确实有小麦,但我只需要这个词本身。不是单词中的术语
  • @ncica,我确实尝试过。问题是它会忽略正确的“-Wheat”选项。

标签: python pandas list iteration


【解决方案1】:

我认为您正在寻找可以通过以下使用re 模块来实现:

import re

def find_word(keyword):
    word = []

    # create a regular expression pattern that would "exactly" match the keyword
    # \b represents Word boundary
    p = re.compile(r'\b{}\b'.format(keyword))

    for i in range(len(df)):
        # use the pattern to search the name
        if p.search(df['name'][i]):
            word.append(df['name'][i])
    return word

find_word("Wheat")
['Cream of Wheat (Quick)', 'Crispy Wheat & Raisins', 'Frosted Mini-Wheat', 
 'Nutri-grain Wheat', 'Puffed Wheat', 'Shredded Wheat', 
 "Shredded Wheat'n'Bran", 'Shredded Wheat spoon size', 'Wheat Chex']

【讨论】:

    【解决方案2】:

    试试这个。

    df[df["name"].str.contains(r'(?:\s|^)Wheat(?:\s|$)')]["name"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-13
      • 2020-10-28
      • 2019-08-26
      • 2017-05-26
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多