只保留以“@here”结尾的行(RegEx,Python)

2024-04-27 13:48:24 发布

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

我有一个几乎有一千行的文本文件,比如:

WorldNews,Current WorldNews,Current,WorldNews@here', 'WorldNewsPro@here Zebra,Poacher', 'Dock,DS_URLs@here' Zebra,Poacher,ZebraPoacher@here Zebra,Dock,ZebraDock@here Timer33,Timer33@here

有时行尾没有“@here”,有时以“@here”结尾,有时在行中间有“@here”,有时行以“@here”结尾

我想去掉所有没有“@这里”的线。我试过正则表达式:

> (^(@here$))  
> [\W](@here)

等等,运气不好。在

我应该如何使用“@here”来拉线,这样我的新文件(或输出)只有:

WorldNews,Current,WorldNews@here', 'WorldNewsProfessional52@here Zebra,Poacher', 'DocuShare,AC_DS_URLs@here' Zebra,Poacher,ZebraPoacher@here Zebra,DocuShare,ZebraDocushare@here XNTimer,XNTimer@here

我想它应该从头到尾读整行,如果行中有@here,就打印出来。如果没有,忽略并阅读下一行。在

谢谢

阿德里安


Tags: here结尾dscurrenturls文本文件zebradock
3条回答

也许这有帮助:(假设filename是输入文件的名称)

with open(filename) as stream:
    for line in stream:
        if '@here' in line:
            print line

您需要in运算符。在

for line in sys.stdin:
  if '@here' in line:
    sys.stdout.write(line)

你不需要正则表达式。您可以使用字符串方法进行简单的筛选:

def hasstr( lines, s ):
    # a generator expression can filter out the lines
    return (line for line in lines if s in line)

# get all lines in the file with @here in them     
filtered = hasstr(open(the_file, 'rt'), '@here')

相关问题 更多 >