python - Python搜索文本列,如果单词列表中有任何匹配的关键字,则返回
问题描述
我有一个包含两列的数据框,message_id 和 msg_lower。我还有一个称为术语的关键字列表。我的目标是在 msg_lower 字段中搜索术语列表中的任何单词。如果它们匹配,我想返回一个包含 message_id 和关键字的元组。
数据如下所示:
|message_id|msg_lower |
|1116193453|text here that means something |
|9023746237|more text there meaning nothing|
terms = [text, nothing, there meaning]
术语也可以长于一个词
对于给定的示例,我想返回:
[(1116193453, text),(9023746237,text),(9023746237,nothing),(9023746237,there meaning)]
理想情况下,我想尽可能有效地做到这一点
解决方案
您可以按元组压缩两列以进行可能的循环,按项循环,并且测试是拆分值中的成员资格:
terms = ['text', 'nothing']
a = [(x,i) for x, y in zip(df['message_id'],df['msg_lower']) for i in terms if i in y.split()]
print (a)
[(1116193453, 'text'), (9023746237, 'text'), (9023746237, 'nothing')]
编辑:
terms = ['text', 'nothing', 'there meaning']
a = [(x, i) for x, y in zip(df['message_id'],df['msg_lower']) for i in terms if i in y]
print (a)
[(1116193453, 'text'), (9023746237, 'text'),
(9023746237, 'nothing'), (9023746237, 'there meaning')]
另一个想法是使用findall
单词边界来提取值:
a = [(x, i) for x, y in zip(df['message_id'],df['msg_lower'])
for i in terms if re.findall(r"\b{}\b".format(i), y)]
推荐阅读
- c++ - 指向某物的奇怪指针模板参数
- windows - MSI 安装程序错误 - MSIExec 失败:1603
- node.js - 转换流中的块会破坏替换尝试吗?
- javascript - 如何一个接一个地执行三个异步函数
- c# - SQL Timeout 比我设置的要长
- json - 如何使用 jq 列出深层嵌套 json 中的所有键?
- youtube-iframe-api - youtube 播放器 api。如果 VIDEO_ID 包含特殊符号,则它不起作用
- node.js - 尝试调用自己的 AWS api 获取 StatusCodeError: 307 Temporary redirect using node request-promise
- javascript - 使用内部 Http 调用测试 RxJS 计时器
- codenameone - 无法为 IOS 构建:xcode 构建步骤失败