简体   繁体   English

如何打印不止一个匹配 python 正则表达式

[英]How to print just more than one match python regex

I have this code, that searches for matches, using regex.我有这段代码,它使用正则表达式搜索匹配项。

with open('ip-new.txt','r') as csvfile1, open('city.txt', 'r', encoding="utf8" ) as file1:
    readCS = csv.reader(csvfile1, delimiter=';')
    reader = file1.readlines()
    for row in readCS:
        for line in reader:
            if all(re.search(fr"\b{word}\b", line, re.IGNORECASE) for word in row[:2]):
                print(str(row) + line)
                

Once i run this i will get the matches i am looking for, but obviously there may be more than one match, so i get the following output:一旦我运行这个我会得到我正在寻找的匹配,但显然可能有不止一个匹配,所以我得到以下 output:

['ZA', 'EAST LONDON'] 'id': 'ZA~EC~East London'

['GB', 'BRIDGWATER'] 'id': 'GB~ENG~Bridgwater'

['GH', 'TEMA'] 'id': 'GH~AA~Tema'

['TH', 'BANGKOK'] 'id': 'TH~10~Bangkok'

['TH', 'BANGKOK'] 'id': 'TH~10~Bangkok Noi'

['TH', 'BANGKOK'] 'id': 'TH~10~Bangkok Yai'

The first 3 matches are uniq, so i dont have the need to print them, I am looking just to print anything that as more than one match.前 3 场比赛是 uniq,所以我不需要打印它们,我只是想打印任何不止一场比赛的东西。 I am not sure how i can fit in a counter a do this with a while loop.我不知道我怎么能适应一个计数器用一个while循环来做到这一点。 as i tried and was unsuccessful.正如我尝试并没有成功。 I may be doing something wrong, not a programmer by any means.我可能做错了什么,无论如何都不是程序员。 Thanks谢谢

Just store the lines in a list and print them if you get more than one:只需将这些行存储在一个列表中,如果您获得多个行,则打印它们:

for row in readCS:
    lines = [line for line in reader
        if all(re.search(fr"\b{word}\b", line, re.IGNORECASE) for word in row[:2])]
    if len(lines) > 1:
        for line in lines:
            print(str(row) + line)

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

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