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

时间:2014-10-29 06:27:09

标签: python regex replace newline

我设法根据数字删除了行,并使用了另一个stackoverflow用户的建议来替换 \n \r < / strong>与&#39; &#39; ...

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

我想转:

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

  

&GT;&GT;你好! &GT;&GT;你好! &GT;&GT;我说的重要事情和   应该是一个完整的句子或段落!这一行是新段落的开头   这不是由任何类型的特殊字符划分的

使用

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()

......我从哪里开始?

2 个答案:

答案 0 :(得分:0)

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

通过添加“ \n ”来尝试此操作。

答案 1 :(得分: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()

这将解决问题。