2016-03-10 27 views
1

我有一個文件,其中一些句子分散在多行中。 例如:連接在一起的行如果它們不是文件中的空格

1:1 This is a simple sentence 
[NEWLINE] 
1:2 This line is spread over 
multiple lines and it goes on 
and on. 
[NEWLINE] 
1:3 This is a line spread over 
two lines 
[NEWLINE] 

所以我希望它看起來像這樣

1:1 This is a simple sentence 
[NEWLINE] 
1:2 This line is spread over multiple lines and it goes on and on. 
[NEWLINE] 
1:3 This is a line spread over two lines 

一些線,分佈在2條或3或4線。如果下面的al行不是新行,它應該合併成一行。 我想覆蓋給定的文件來創建一個新的文件。

我試過了,但沒有成功。

input = open(file, "r") 
zin = "" 
lines = input.readlines() 
#Makes array with the lines 
for i in lines: 
    while i != "\n" 
     zin += i 
..... 

但是這會造成無限循環。

+0

我編輯了我的帖子 –

+0

您可以使用正則表達式並刪除單個/ n或/ r – dnit13

+0

您是如何確定句子實際上位於多行的?這不會與我計算...文件中必須有行尾字符,例如\ n或\ r(或兩者)...除非您使用的編輯器根據寬度來「換行」屏幕上的編輯...例如如果您在Windows上使用notepad.exe等工具,則在「格式」下拉菜單中會有一個「Word Wrap」功能。如果選擇了它,它將根據窗口寬度包裝句子。請仔細檢查您的文件,以確保「包裝的句子」不是由於您用來查看的工具。 HTH,Edwin。 –

回答

3

您不應該在您的用例中嵌套forwhile循環。在你的代碼中會發生什麼,一行通過for循環被分配給變量i,但是它沒有被嵌套的while循環修改,所以如果while子句是,那麼它將保持這種方式並且沒有破壞的條件,你最終將無限循環。

一個解決方案可能是這樣的:

single_lines = [] 
current = [] 

for i in lines: 
    i = i.strip() 
    if i: 
     current.append(i) 
    else: 
     if not current: 
      continue # treat multiple blank lines as one 
     single_lines.append(' '.join(current)) 
     current = [] 
else: 
    if current: 
     # collect the last line if the file doesn't end with a blank line 
     single_lines.append(' '.join(current)) 

覆蓋輸入文件將自行收集在內存中所有的輸出,讀出後關閉該文件並重新打開它的文筆,或者到好辦法在讀取輸入時寫入另一個文件,並在關閉兩者後重命名第二個文件以覆蓋第一個文件。

+0

奧克,但你會如何建議做一個新的文件/覆蓋其他文件。所以我得到想要的「語法」 –

+0

請參閱我的答案的更新。 –

+0

current.append(i)確實給出了一個錯誤「AttributeError:'str'object has no attribute'append'」 –

相關問題