【问题标题】:Finding exact word in description column of DataFrame in Python在 Python 中的 DataFrame 的描述列中查找确切的单词
【发布时间】:2021-01-24 18:40:29
【问题描述】:

我的列表包含一些词,例如:[‘orange’, ‘cool’, ‘app’....],我想从 DataFrame 的描述列中输出所有这些确切的完整词(如果可用)。

我还附上了带有代码的示例图片。我用了str.findall(),如图所示,它从additional中提取add,从apple中提取app。但是,我不希望那样。它应该只在匹配整个单词时才输出。

【问题讨论】:

    标签: python regex pandas findall exact-match


    【解决方案1】:

    您可以使用修复代码

    df['exactmatch'] = df['text'].str.findall(fr"\b({'|'.join(list1)})\b").str.join(", ")
    

    或者,如果您的 list1 字词中有特殊字符,

    df['exactmatch'] = df['text'].str.findall(fr"(?<!\w)({'|'.join(map(re.escape, list1))})(?!\w)").str.join(", ")
    

    fr"\b({'|'.join(list1)})\b"fr"(?&lt;!\w)({'|'.join(map(re.escape, list1))})(?!\w)" 创建的模式如下所示

    \b(orange|cool|app)\b
    (?<!\w)(orange|cool|app)(?!\w)
    

    请参阅regex demo。注意 .str.join(", ") 被认为比 .apply(", ".join) 快。

    【讨论】:

    • 谢谢!但是,如果我的文本也有带连字符的单词,例如附加材料,或复数,例如苹果,我怎样才能修改我的搜索,而不是在我的 list1 中有“附加材料和苹果”,但仍然得到输出附加材料和苹果。谢谢!
    • @ShrestR 试试r"(?&lt;!\w)(" + '|'.join([re.escape(x).replace('\\ ', r'[\s-]') for x in list1]) + r")"
    • 嗨,如何在 pyspark df 中进行相同的精确匹配操作?以下是熊猫: df['exactmatch'] = df['text'].str.findall(fr"(?
    • @ShrestR 我不太了解 pyspark,我认为您应该使用 pyspark.sql.functions.regexp_replace 之类的 regexp_replace(col, fr"(?s)(?&lt;!\w)({'|'.join(map(re.escape, list1))})(?!\w)|.?", r"\1, ") 并且此值也应替换为 regexp_replace(&lt;the-result-of the previous substitution&gt;, '^(?:, )+|(?:, )+$|(, )+', r'\1')
    猜你喜欢
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多