2015-11-14 59 views
-2
''' 
    This is single line. 
    This is second long line 
    ... continue from previous line. 
    This third single line. 
''' 

我想連接用省略號(...)分開的行。這我想用Python做。長行由新行(\ n)和省略號(...)分隔。我正在逐行閱讀該文件,並在特定行上執行一些操作,但以新行(\ n)繼續行結束,下一行以省略號(...)開始。正因爲如此,我無法獲得全線做具體操作。如何加入繼續線與Python中的省略號(...)

我作爲例子的線條來自大文件(超過800行)。 python實用程序解析文件,搜索具有特定關鍵字的行,並用新語法替換該行的一部分。這我想對多個文件做。

請告訴我。

+0

你是什麼意思*加入行*? 'text.split( '...')'? –

+0

你的意思是「這是第二長線」,並且......從前一行繼續。 '應該是'這是繼續前一行的第二條長線。'? –

+0

@Kevin,是的,我想要相同的輸出。 –

回答

0

您可以分割線斷行,然後通過循環,並添加省略號線前行,像這樣:

lines = lines.split('\n') 
for i, line in enumerate(lines): 
    line = line.strip().lstrip() 
    if line.startswith('...') and i != 0: 
     lines[i - 1] = lines[i - 1].strip().lstrip() + line.replace('...', '') 
     del lines[i] 
+0

謝謝你,它適合我。 –

3

你可以簡單地做:

delim = '...' 
text = '''This is single line. 
      This is second long line 
      ... continue from previous line. 
      This third single line. 
     ''' 

# here we're building a list containing each line 
# we'll clean up the leading and trailing whitespace 
# by mapping Python's `str.strip` method onto each 
# line 
# this gives us: 
# 
# ['This is single line.', 'This is second long line', 
# '... continue from previous line.', 'This third single line.', ''] 
cleaned_lines = map(str.strip, text.split('\n')) 

# next, we'll join our cleaned string on newlines, so we'll get back 
# the original string without excess whitespace 
# this gives us: 
# 
# This is single line. 
# This is second long line 
# ... continue from previous line. 
# This third single line. 
cleaned_str = '\n'.join(cleaned_lines) 

# now, we'll split on our delimiter '...' 
# this gives us: 
# 
# ['This is single line.\nThis is second long line\n', 
# ' continue from previous line.\nThis third single line.\n'] 
split_str = cleaned_str.split(delim) 

# lastly, we'll now strip off trailing whitespace (which includes) 
# newlines. Then, we'll join our list together on an empty string 
new_str = ''.join(map(str.rstrip, split_str)) 

print new_str 

其輸出

This is single line. 
This is second long line continue from previous line. 
This third single line. 
+0

這不會在「這是第二長行」後刪除新行。所以它實際上返回: 這是單行。\ n 這是第二條長行\ n 從上一行繼續。\ n 第三條單行。 – sundance

+0

好點@sundance!編輯。 –

+1

@Michael,感謝您提供非常整潔和詳細的答案。我用過的例子來自大文件(超過800行)。 python實用程序解析文件,搜索具有特定關鍵字的行,並用新語法替換該行的一部分。這我想對多個文件做。 –