Regex从元组列表中捕获包含特定模式的元组

2024-10-03 13:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表:

ee = [('noise', 0.7592900395393372), ('***roice***', 0.638433039188385), ('voice', 0.7524746060371399), ('***choice***', 0.638433039188385)]

从这里,我只想提取包含以***开头的模式的元组

预期产出:

ee = [('***roice***', 0.638433039188385), ('***choice***', 0.638433039188385)]

我尝试了下面的正则表达式,但它只捕获带***的单词,而不是整个元组,也就是说,我还希望在包含***的元组中出现数字

迄今为止的代码:

yy= []
for i in ee:
    t9 = re.findall("[***@*&?].*[***@*&?, ]", str(i))
#    for m in t9.finditer(t9):
#        print(m.start(), m.group())
#    
#    print(t9)
    for em in t9:
        yy.append(em)

有人能帮我修一下吗


Tags: in列表for模式单词ee元组print
3条回答

您可以尝试:

ee = [('noise', 0.7592900395393372), ('***roice***', 0.638433039188385), ('voice', 0.7524746060371399), ('***choice***', 0.638433039188385)]

output = []

for data in ee:
    if data[0].startswith("***")::
        output.append(data)
print(output)

输出:

[('***roice***', 0.638433039188385), ('***choice***', 0.638433039188385)]

如果需要提取0元素以***开头和结尾的元组, 您可以尝试以下方法:

extracted = []
for item in ee:
    if item[0][:3] == '***' and item[0][-3:] == '***':
        extracted.append(item)

这不使用正则表达式

我不确定在这种情况下你是否需要正则表达式。如果您只想过滤以“***”开头的字符串,只需执行以下操作:

[e for e in ee if e[0].startswith('***')]

如果仍要使用正则表达式,可以执行以下操作:

r = re.compile(r'\*\*\*.*\*\*\*')
[s for s in ee if r.match(s[0])]

相关问题 更多 >