You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Pandas DataFrame与短语列表的匹配?

解决Pandas DataFrame与短语列表的匹配问题

我明白你的问题了——当匹配列表是多单词短语而非单个单词时,之前依赖nltk.word_tokenize()拆分单个单词匹配的方法就失效了,因为分词后只能识别独立单词,没法处理短语级别的匹配。下面根据你的场景给出两种针对性的解决方案:

场景1:匹配连续的短语子串

如果你的短语是句子中连续出现的内容(比如假设你的列表是['is blue', 'is green']),可以直接检查短语是否是文本的子字符串:

import pandas as pd

frame = pd.DataFrame({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']})
mylist = ['cat blue', 'sky green', 'dog black']

# 定义函数:找出文本中包含的连续短语
def find_continuous_phrases(text, phrase_list):
    return [phrase for phrase in phrase_list if phrase in text]

# 应用到DataFrame的a列
frame['Data'] = frame['a'].apply(lambda x: find_continuous_phrases(x, mylist))
print(frame)

不过注意:在你的例子中,cat blue并不是句子the cat is blue里的连续子串(中间隔了is),所以这个方法不会返回匹配结果。如果你的实际需求是只要句子包含短语里的所有单词(不管顺序和间隔),请用下面的方案。

场景2:匹配包含短语所有单词的文本

针对你给出的例子(短语是两个单词,对应句子里都包含这两个单词),我们可以先把短语拆成单词集合,再检查文本是否包含短语的所有单词:

import pandas as pd
import nltk
from nltk.tokenize import word_tokenize

frame = pd.DataFrame({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']})
mylist = ['cat blue', 'sky green', 'dog black']

# 预先把每个短语转换成单词集合,方便后续匹配
phrase_word_sets = {phrase: set(word_tokenize(phrase)) for phrase in mylist}

def find_matching_phrases(text):
    # 把当前文本也转换成单词集合
    text_words = set(word_tokenize(text))
    # 筛选出所有单词集合都被文本包含的短语
    return [phrase for phrase, words in phrase_word_sets.items() if words.issubset(text_words)]

# 应用函数到DataFrame
frame['Data'] = frame['a'].apply(find_matching_phrases)
print(frame)

运行这段代码后,你会得到预期的结果:

a        Data
0  the cat is blue  [cat blue]
1  the sky is green  [sky green]
2  the dog is black  [dog black]

这个方法的优势在于:不管短语里的单词在句子中的位置和间隔,只要所有单词都存在,就会匹配成功,完美适配你的示例场景。

内容的提问来源于stack exchange,提问作者Syed Jameer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:25:08