2012-09-16 49 views
1
abc=123 
dabc=123 
    abc=456 
    dabc=789 
    aabd=123 

从上面的文件,我需要找到线与ABC开始=(空格无所谓)Python替换rubys grep?

在Ruby中,我会把这个阵列中的和做

matches = input.grep(/^\s*abc=.*/).map(&:strip) 

我在Python中完全没有人,甚至说我是一个新鲜的Python开发人员太多了。

也许有一个更好的“Python方式”做到这一点,甚至没有grepping?

的Python版本我提供的平台,在这里,我需要解决的问题上是2.6

没有使用Ruby的方式在当时

+0

这是你想要的吗? http://stackoverflow.com/questions/1921894/grep-and-python –

+0

谢谢!,肯定会帮我解决 – astropanic

回答

5
with open("myfile.txt") as myfile: 
    matches = [line.rstrip() for line in myfile if line.lstrip().startswith("abc=")] 
+1

+1为了清晰起见。我会使用'打开(“myfile.txt”)作为myfile'。 – dokkaebi

+0

好点,改变了它。 – kindall

+0

非常感谢!这是结果:https://github.com/astropanic/Compline正如我所说,我不是一个Python专家,所以请忍受我;) – astropanic

1

在Python中,你通常会使用列表理解其if子句做你会用Ruby的grep完成:

import sys, re 
matches = [line.strip() for line in sys.stdin 
      if re.match(r'^\s*abc=.*', line)]