2014-10-29 70 views
0

我已經成功地去掉基於數字線,以及使用其他計算器用戶的建議,以取代\n\r與「」 ......Python - 刪除行之前的換行符?

如何使用某行之前保留換行符某些字符

我想轉:

1 
00:00:01,790 --> 00:00:03,400 
\>> Hello there! 
2 
00:00:03,400 --> 00:00:05,140 
\>> Hi you! 
3 
00:00:05,140 --> 00:00:07,600 
\>> Important things that I am saying and 
should be a complete sentence or paragraph! 
! 
4 
This line is the start of a new paragraph 
That isn't delimited by any sort of special characters 

\>> Hello there! 
\>> Hi you! 
\>> Important things that I am saying and 
should be a complete sentence or paragraph!! 
This line is the start of a new paragraph 
That isn't delimited by any sort of special characters 

到目前爲止,我可以得到:

>>你好! >>你好! >>我說的重要的事情和 應該是一個完整的句子或段落!這條線是不是任何形式的特殊字符

使用

print "Please enter full filename with extension" 
file = raw_input("> ") 
with open (file, "r") as myfile: 
    data=myfile.readlines() 
x = '' 
for line in data: 
    if line[:1].isdigit() == False: 
     x += line 

y = '' 
for line in x[1:]: 
    if line[:2] == '>>': 
     y += line.replace('\n', ' ').replace('\r', '') 
    else: 
     y += ("\r" + line) 


file_ = open('finished.txt', 'w+') 
file_.write(y) 
file_.close() 

...我在哪裏從這裏去界定一個新的段落 的開始?

+0

你能檢查你的問題是否被正確編輯好嗎?通常,最好使用代碼格式而不是引號格式來避免字符消失(例如,如果引號格式中有多個換行符,則只會顯示1個換行符,但代碼格式化不是這種情況)。 – Jerry 2014-10-29 07:43:34

回答

0
for line in x[1:]: 
    if line[:2] == '>>': 
     y += line.replace('\n', ' ').replace('\r', '') + '\n' 
    else: 
     y += ("\r" + line) + '\n' 

加入了 '\n' 背後試試這個。

0

請勿使用下面的代碼部分。如果沒有這幾行代碼正常工作:

#Remove these lines 
y = ''  
for line in x[1:]: 
    if line[:2] == '>>': 
     y += line.replace('\n', ' ').replace('\r', '') 
    else: 
     y += ("\r" + line) 

這裏是你的代碼的其餘部分的演示:

>>> fp=open('a','r') 
>>> data=fp.readlines() 
>>> data 
['1\n', '00:00:01,790 --> 00:00:03,400\n', '\\>> Hello there!\n', '2\n', '00:00:03,400 --> 00:00:05,140\n', '\\>> Hi you!\n', '3\n', '00:00:05,140 --> 00:00:07,600\n', '\\>> Important things that I am saying and \n', 'should be a complete sentence or paragraph! \n', '!\n', '4\n', 'This line is the start of a new paragraph\n', "That isn't delimited by any sort of special characters\n"] 
>>> x = '' 
>>> for line in data: 
...  if line[:1].isdigit() == False: 
...   x += line 
... 
>>> fp.close() 
>>> print x 
\>> Hello there! 
\>> Hi you! 
\>> Important things that I am saying and 
should be a complete sentence or paragraph! 
! 
This line is the start of a new paragraph 
That isn't delimited by any sort of special characters 

>>> fp.close() 

現在更換下面三行:

file_ = open('finished.txt', 'w+') 
file_.write(y) 
file_.close() 

有:

>>> file_=open('finished.txt','w+') 
>>> for line in x: 
... file_.write(line) 
... 
>>> file_.close() 

這將修復問題。