2012-04-18 39 views
0

我有以下文件:如何複製多行?

this is the first line 
and this is the second line 
now it is the third line 
wow, the fourth line 
but now it's the fifth line 
etc... 
etc... 
etc... 

從「現在是第三行」到「但現在它的第五行」,我怎麼複製這些三線(如果不知道的行號開始線)?在perl中,你會這樣做:

/^now it is/../^but now/ 

python中的等效函數是什麼?

我有(這顯然只抓住線1):

regex = re.compile("now it is") 
for line in content: 
    if regex.match(line): 
     print line 

編輯:

reg = re.compile(r"now it is.*but now it.*", re.MULTILINE | re.DOTALL) 

matches = reg.search(urllib2.urlopen(url).read()) 
for match in matches.group(): 
    print match 

此打印:

n 
o 
w 

i 
t 

i 
s 

. 
. 
. 

即它返回字符,而不是全線

回答

2

我想你只需要看到re.MULTILINE flag。感謝它,您可以執行類似的匹配並從您想要的行中獲取組合的文本。

編輯:

完整的解決方案包括使用re.MULTILINEre.DOTALL標誌,加上非貪婪正則表達式:

>>> text = """this is the first line 
and this is the second line 
now it is the third line 
wow, the fourth line 
but now it's the fifth line 
etc... 
etc... 
etc...""" 
>>> import re 
>>> match = re.search('^(now it is.*?but now.*?)$', text, flags=re.MULTILINE|re.DOTALL) 
>>> print match.group() 
now it is the third line 
wow, the fourth line 
but now it's the fifth line 
+0

這看起來不錯,但我不太清楚如何使用它....像re.compile(r「^現在是。*但現在$」,re.MULTILINE)? – 2012-04-19 00:10:03

+0

@ user522962:類似的東西,但你也應該添加另一個標誌(['re.DOTALL'](http://docs.python.org/library/re.html#re.DOTALL)),這將使' .'匹配_newline_字符,並且還應該在'$'之前添加'。*'以匹配最後一行的剩餘部分。你想看到完整的解決方案嗎?或者這對解決問題來說足夠了嗎? – Tadeck 2012-04-19 00:50:10

+0

我已經給它一個鏡頭......看到我的編輯在我的問題....我做錯了什麼。 – 2012-04-19 02:03:47

1
f = open("yourfile") #that is, the name of your file with extension in quotes 
f = f.readlines() 

現在f將是文件中每行的列表。 f [0]將是第一行,f [1]是第二行,依此類推。要抓住第三線到第五線,你會使用f [2:5]

+0

我剛做了一個編輯....如果我不知道行數(我不知道),我該怎麼做呢? – 2012-04-18 23:47:36

+0

@ user522962如果您嘗試通過字符串內容匹配,請在f中的行上運行for循環,詢問字符串內容是否符合您的期望。我很抱歉,因爲如果你不想按照內容或行號匹配,我不知道你在問什麼。 – purpleladydragons 2012-04-18 23:53:23

+1

我建議不要使用readlines(),因爲它將整個文件放在內存中。根據文件的大小,這可能是一個問題。 – 2012-04-18 23:54:27

1

這樣的事情?

import re 
valid = False 
for line in open("/path/to/file.txt", "r"): 
    if re.compile("now it is").match(line): 
     valid = True 
    if re.compile("but now").match(line): 
     valid = False 
    if valid: 
     print line 

你這樣的緩存在同一時間只有一條線路,相反使用readlines()在那裏你會在內存中緩存整個文件。

這是假設正則表達式模式在您的文本塊中是唯一的,如果不是這種情況,請提供更多關於您如何匹配起始行和結束行的信息。

如果你只需要檢查匹配行的開頭那就更簡單了:

valid = False 
for line in open("/path/to/file.txt", "r"): 
    if line.startswith("now it is"): 
     valid = True 
    if line.startswith("but now"): 
     valid = False 
    if valid: 
     print line 
2

,你可以很容易地使發電機來做到這一點

def re_range(f, re_start, re_end): 
    for line in f: 
     if re_start.match(line): 
      yield line 
      break 
    for line in f: 
     yield line 
     if re_end.match(line): 
      break 

,你可以這樣稱呼它

import re 

re_start = re.compile("now it is") 
re_end = re.compile("but now") 
with open('in.txt') as f: 
    for line in re_range(f, re_start, re_end): 
     print line,