2012-09-16 83 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)]