以下代码允许我通过搜索包含单词“cod”或“i”的行来成功识别 pandas 数据框中的第二个和第三个文本,并且仅识别这些文本:
import numpy as np
import pandas as pd
texts_df = pd.DataFrame({"id":[1,2,3,4],
"text":["she loves coding",
"he was eating cod",
"i do not like fish",
"fishing is not for me"]})
texts_df.loc[texts_df["text"].str.contains(r'\b(cod|i)\b', regex=True)]
我想通过从长列表中插入单词来动态构建单词列表,但我不知道如何成功做到这一点。
我已经尝试了以下操作,但出现错误,提示“r 未定义”(我期望它不是变量,但我也不能将其作为字符串的一部分,并且不知道应该做什么)
kw_list = ["cod", "i"]
kw_regex_string = "\b("
for kw in kw_list:
kw_regex_string = kw_regex_string + kw + "|"
kw_regex_string = kw_regex_string[:-1] # remove the final "|" at the end
kw_regex_string = kw_regex_string + ")\b"
myregex = r + kw_regex_string
texts_df.loc[texts_df["text"].str.contains(myregex, regex=True)]
如何构建包含关键字列表的“或”条件,然后以适用于 pandas 数据框搜索的方式将其插入到 reg ex 中?
当我这样做时,我用
map
和 re.escape
包裹列表以转义可能具有正则表达式含义的特殊字符,然后将其包含在括号中:
import re
kw_list = ['cod', 'i']
my_regex = r'\b(?:%s)\b' % '|'.join(map(re.escape, kw_list))
texts_df.loc[texts_df['text'].str.contains(my_regex, regex=True)]