Python-在一行之前删除换行符?

Python-在一行之前删除换行符?,python,regex,replace,newline,Python,Regex,Replace,Newline,我已成功删除基于数字的行,并使用另一个stackoverflow用户的建议将\n和\r替换为 如何在具有特定字符的特定行之前保留换行符 我想谈谈: 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 tha

我已成功删除基于数字的行,并使用另一个stackoverflow用户的建议将\n和\r替换为

如何在具有特定字符的特定行之前保留换行符

我想谈谈:

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
到目前为止,我可以得到:

>>你好!>>你好!>>我要说的重要事情和 应该是完整的句子或段落!!这一行是新段落的开头 它不由任何特殊字符分隔

使用

…我该怎么办

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

请尝试在后面添加“\n”

不要使用代码的以下部分。如果没有这些行,代码将正常工作:

#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()
与:


这将解决此问题。

请检查您的问题是否已正确编辑,好吗?通常,最好使用代码格式而不是引号格式,以避免字符消失。例如,如果引号格式中有多个换行符,则只显示1,但代码格式并非如此。
file_ = open('finished.txt', 'w+')
file_.write(y)
file_.close()
>>> file_=open('finished.txt','w+')
>>> for line in x:
...    file_.write(line)
... 
>>> file_.close()