【发布时间】:2021-12-15 19:58:03
【问题描述】:
我很难将 DataFrame 列中的字符串与字符串列表进行比较。
让我给你解释一下: 我从社交媒体收集了个人项目的数据,除此之外,我还创建了一个字符串列表,如下所示:
the_list = ['AI', 'NLP', 'approach', 'AR Cloud', 'Army_Intelligence', 'Artificial general intelligence', 'Artificial tissue', 'artificial_insemination', 'artificial_intelligence', 'augmented intelligence', 'augmented reality', 'authentification', 'automaton', 'Autonomous driving', 'Autonomous vehicles', 'bidirectional brain-machine interfaces', 'Biodegradable', 'biodegradable', 'Biotech', 'biotech', 'biotechnology', 'BMI', 'BMIs', 'body_mass_index', 'bourdon', 'Bradypus_tridactylus', 'cognitive computing', 'commercial UAVs', 'Composite AI', 'connected home', 'conversational systems', 'conversational user interfaces', 'dawdler', 'Decentralized web', 'Deep fakes', 'Deep learning', 'defrayal']
还有其他词,但这只是给你一个想法。
我的目标是将此列表中的每个单词与 2 个现有的 DF 列进行比较,其中包含标题和帖子消息(来自 reddit)。为了清楚起见,我想创建一个新列,在其中显示在我的列表与包含帖子的列之间匹配的单词。
到目前为止,这就是我所做的:
the_list = ['AI', 'NLP', 'approach', 'AR Cloud', 'Army_Intelligence', 'Artificial general intelligence', 'Artificial tissue', 'artificial_insemination', 'artificial_intelligence', 'augmented intelligence', 'augmented reality', 'authentification', 'automaton', 'Autonomous driving', 'Autonomous vehicles', 'bidirectional brain-machine interfaces', 'Biodegradable', 'biodegradable', 'Biotech', 'biotech', 'biotechnology', 'BMI', 'BMIs', 'body_mass_index', 'bourdon', 'Bradypus_tridactylus', 'cognitive computing', 'commercial UAVs', 'Composite AI', 'connected home', 'conversational systems', 'conversational user interfaces', 'dawdler', 'Decentralized web', 'Deep fakes', 'Deep learning', 'defrayal']
df['matched text'] = df.text_lemmatized.str.extract('({0})'.format('|'.join(the_list)), flags = re.IGNORECASE)
df = df[~pd.isna(df['matched text'])]
df
>>Outpout:
title_lemmatized text_lemmatized matched_word(s)
0 Title1 'claim thorough vet...' 'ai'
1 Title@ 'Yeaaah today iota...' 'IoT'
Here the output result for more details.
问题:主要问题是它返回给我的字母(不是实际单词)与列表匹配。
例子:
--> the_list = 'ai'(用于人工智能)或 IoT(用于物联网)
--> df['text_lemmatized'] 在文本中有单词 'claim',那么 'ai' 将是匹配项。或“Iota”将与“IoT”匹配。
我的愿望:
title_lemmatized text_lemmatized matched_word(s)
0 Title1 'AI claim that Iot devises...' 'AI', 'IoT'
1 Title2 'The claim story about...'
2 Title3 'augmented reality and ai are...' 'augmented reality', 'ai'
3 Title4 'AI ai or artificial intelligence' 'AI', 'ai', 'artificial intelligence'
非常感谢:)
【问题讨论】:
-
你必须使用regex word boundaries
\b。试试r'\b({0})\b'.format('|'.join(the_list))。 -
谢谢哈利,我知道它是从哪里来的。简单地从'|'而不是 ' | '。
标签: python pandas dataframe string-matching