python - 正则表达式 Python - 从字符串列表中返回带有关键字的元组
问题描述
我有一个关键字列表,我想解析关键字的长字符串列表、货币格式的价格以及字符串中小于 10 的任何其他数字。例如:
keywords = ['Turin', 'Milan' , 'Nevada']
strings = ['This is a sentence about Turin with 5 and $10.00 in it.', ' 2.5 Milan is a city with £1,000 in it.', 'Nevada and $1,100,000. and 10.09']]
希望会返回以下内容:
final_list = [('Turin', '$10.00', '5'), ('Milan', '£1,000', '2.5'), ('Nevada', '$1,100,000', '')]
我有以下功能正则表达式,但我不知道如何将输出组合到元组列表中。有没有更简单的方法来实现这一点?我应该按单词拆分然后寻找匹配项吗?
def find_keyword_comments(list_of_strings,keywords_a):
list_of_tuples = []
for string in list_of_strings:
keywords = '|'.join(keywords_a)
keyword_rx = re.findall(r"^\b({})\b$".format(keywords), string, re.I)
price_rx = re.findall(r'^[\$\£\€]\s?\d{1,3}(?:[.,]\d{3})*(?:[.,]\d{1,2})?$', string)
number_rx1 = re.findall(r'\b\d[.]\d{1,2}\b', string)
number_rx2 = re.findall(r'\s\d\s', string)
解决方案
您可以使用re.findall
:
import re
keywords = ['Turin', 'Milan' , 'Nevada']
strings = ['This is a sentence about Turin with 5 and $10.00 in it.', '2.5 Milan is a city with £1,000 in it.', 'Nevada and $1,100,000. and 10.09']
grouped_strings = [(i, [b for b in strings if i in b]) for i in keywords]
new_groups = [(a, filter(lambda x:re.findall('\d', x),[re.findall('[\$\d\.£,]+', c) for c in b][0])) for a, b in grouped_strings]
last_groups = [(a, list(filter(lambda x:re.findall('\d', x) and float(x) < 10 if x[0].isdigit() else True, b))) for a, b in new_groups]
输出:
[('Turin', ['5', '$10.00']), ('Milan', ['2.5', '£1,000']), ('Nevada', ['$1,100,000.'])]
推荐阅读
- javascript - 用的地方多的接口存放在哪里
- ruby-on-rails - Ruby on rails,如何在没有关联的情况下查询数据库中的对象?
- node.js - 使用nodejs在lambda函数中发送邮件
- macos - 错误:您必须在按 Tab 键时为容器指定至少一个命令
- javascript - 当从桌面调整到移动时,将幻灯片项目分离为 2 个横幅,反之亦然
- python-3.x - 访问字典列表中的所有元素,以及字典中的字典
- javascript - 纯 JS 处理如果内容文本长度 < 0 然后隐藏
- php - 如何在使用 PHP 中的块拆分的不同条件下使用 for 循环多个条件
- apollo - 如何在 SvelteKit 中初始化 ApolloClient 以同时在 SSR 和客户端上工作
- python - 下次如何保存kivy中的更改