微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用正则表达式将单词列表与另一个单词列表进行比较并打印匹配项?

如何解决如何使用正则表达式将单词列表与另一个单词列表进行比较并打印匹配项?

如何使用正则表达式将单词列表与另一个单词列表进行比较并打印匹配项?

我有一个关键字列表:

test_keywords=["buy house in kings landing","house price kings landing","cost of living kings landing","wildfire pricing"]

我有一个包含关键字的列表:

i_transactional = ["buy","Buy","price","Price","cost","Cost","pricing","Pricing","cheap","Cheap"]

我想使用正则表达式模块在 test_keywords 中查找 i_transactional 中的单词。

我在一个结构中工作,我在 re.compile 中手动输入来自 i_transactional 的关键字:

# create a regex
r_t = re.compile (r'buy|Buy|price|Price|cost|Cost|pricing|Pricing|cheap|Cheap')

# use list to find the regex words in the test_keywords list
o_t = list(filter(r_t.findall,test_keywords))

# print the results of the regex lookup
print("Transactional (",len(o_t),") = ",o_t)

输出

事务性 (5) = ['买房国王登陆'、'房价国王登陆'、'生活成本国王登陆'、'野火定价']

但我希望 r_t 使用 i_transactional 列表,而不是在正则表达式中手动输入单词。

我已经在下面的结构中尝试过,但不起作用。

# create a regex
r_tl = re.compile(r"\<i_transactional>") #transactional

# use list to find the regex words in the test_keywords list
o_tl = list(filter(r_tl.findall,len(o_tl),o_tl)

这段代码有问题。

输出

事务性 (0) = []

如何使用正则表达式将单词列表与另一个单词列表进行比较并打印匹配项?

提前致谢。

解决方法

您可以使用 string.join 通过 | 加入列表并创建正则表达式。

r_t = re.compile ('|'.join(i_transactional))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。