如果与python中的模式匹配,则返回行

2024-10-02 22:35:07 发布

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

如果模式匹配,如何打印文件中的行?但有一个警告。搜索不应考虑文件行中的任何括号。 我的搜索模式是CurrentPrincipalLegalEventAssociation

这是文件的内容

941,agg.list,CurrentPrincipalMailingAddressStreetLine1,CompanyElementDefinition
c755ad,atom.list,CurrentPrincipal[LegalEventAssociation][Type][*],CompanyElementDefinition
8798c3,atom.list,CurrentPrincipal[MailingAddressStreetLine1][*],CompanyElementDefinition
2e43d1,atom.list,CurrentPrincipal[MailingAddressStreetLine2][*],CompanyElementDefinition
b3a13b,atom.list,CurrentPrincipal[MailingContinentName][*],CompanyElementDefinition

当我做搜索它应该返回我下面的一行 c755ad,atom.list,CurrentPrincipal[LegalEventAssociation][Type][*],CompanyElementDefinition

这里的模式没有任何括号,但是,我想要的行中有括号。我正在寻找一个程序,可以忽略括号,而匹配的模式。你知道吗

我是python新手,我所知道的只是打印一行,如果它匹配一个特定的单词,但不是这种类型的。 这是我尝试过的,但没有成功。你知道吗

for line in file.splitlines():
    if "CurrentPrincipalLegalEventAssociation" in line:
        print line

Tags: 文件in警告内容typeline模式list
1条回答
网友
1楼 · 发布于 2024-10-02 22:35:07

这应该满足您的需要:

with open(filename) as myfile:
    for row in myfile:
        if 'CurrentPrincipalLegalEventAssociation' in row.replace('[', '').replace(']', ''):
            print(row)

这将遍历文件中的行,在删除方括号后检查字符串,如果找到匹配项,则返回匹配项。你知道吗

相关问题 更多 >