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

时间:2011-03-05 03:37:44

标签: python regex

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

  

世界新闻,电流   世界新闻,当前,世界新闻@这里”,   'WorldNewsPro @ here Zebra,Poacher',   '码头,DS_URLs @这里'   斑马,偷猎者,ZebraPoacher @这里   斑马,码头,ZebraDock @这里   Timer33,Timer33 @这里

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

我想要删除所有没有“@here”的行。我试过RegEx:

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

等。没有运气。

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

  

世界新闻,电流,世界新闻@这里”,   “WorldNewsProfessional52 @这里   斑马,偷猎者,   '文件分享,AC_DS_URLs @这里'   斑马,偷猎者,ZebraPoacher @这里   斑马,文件分享,ZebraDocushare @这里   XNTimer,XNTimer @这里

我在想它应该从头到尾读取整行,如果它在行中的任何地方都有,请打印出来。如果没有,请忽略并阅读下一行。

谢谢,

阿德里安

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

你不需要正则表达式。您可以使用字符串方法执行此类简单过滤:

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')

答案 2 :(得分:1)

您需要in运算符。

for line in sys.stdin:
  if '@here' in line:
    sys.stdout.write(line)
相关问题