简体   繁体   English

正则表达式从元组列表中捕获包含特定模式的元组

[英]Regex to capture a tuple containing a particular pattern from a list of tuples

I have a list of tuples:我有一个元组列表:

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

From here I want to extract only the tuples that contains the pattern which starts with ***从这里我想只提取包含以 *** 开头的模式的元组

Expected output:预期 output:

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

I have tried the following regex but it only captures the words with *** but not the entire tuple, ie I also want the number present in the tuple which contains ***.我尝试了以下正则表达式,但它只捕获带有 *** 的单词而不是整个元组,即我还希望包含 *** 的元组中存在数字。

Code till now:到目前为止的代码:

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)

Can someone help me fix this有人可以帮我解决这个问题吗

You can try:你可以试试:

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)

Output: Output:

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

I'm not sure you want a regex in this case.在这种情况下,我不确定您是否需要正则表达式。 If all that you want to do is filtering strings that begin with "***", you can simply do:如果您只想过滤以“***”开头的字符串,您可以简单地执行以下操作:

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

If you still want to use a regex, you can do:如果您仍想使用正则表达式,您可以执行以下操作:

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

if you need to extract the tuples which 0 element starts and ends with *** , you can try with this:如果您需要提取 0 元素以***开头和结尾的元组,您可以尝试以下操作:

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

This doesn't use regex.这不使用正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM