如何从文本文件中删除^ M并将其替换为下一行

时间:2021-12-03 23:26:35

So suppose I have a text file of the following contents:

所以假设我有一个以下内容的文本文件:

Hello what is up. ^M
^M
What are you doing?

I want to remove the ^M and replace it with the line that follows. So my output would look like:

我想删除^ M并将其替换为后面的行。所以我的输出看起来像:

Hello what is up. What are you doing?

How do I do the above in Python? Or if there's any way to do this with unix commands then please let me know.

我如何在Python中执行上述操作?或者,如果有任何方法使用unix命令,请告诉我。

3 个解决方案

#1


7  

''.join(somestring.split(r'\r'))

or

somestring.replace(r'\r','')

This assumes you have carriage return characters in your string, and not the literal "^M". If it is the literal string "^M" then substiture r'\r' with "^M"

假设您的字符串中有回车符,而不是文字“^ M”。如果它是文字字符串“^ M”那么替换r'\ r'和“^ M”

If you want the newlines gone then use r'\r\n'

如果你想要换行,那就用r'\ r \ n'

This is very basic string manipulation in python and it is probably worth looking at some basic tutorials http://mihirknows.blogspot.com.au/2008/05/string-manipulation-in-python.html

这是python中非常基本的字符串操作,可能值得查看一些基本的教程http://mihirknows.blogspot.com.au/2008/05/string-manipulation-in-python.html

And as the first commenter said its always helpful to give some indication of what you have tried so far, and what you don't understand about the problem, rather than asking for an straight answer.

正如第一位评论者所说,它总是有助于给出你到目前为止所尝试的内容的一些指示,以及你对这个问题不了解的内容,而不是直截了当地回答问题。

#2


6  

Try:

>>> mystring = mystring.replace("\r", "").replace("\n", "")

(where "mystring" contain your text)

(“mystring”包含你的文字)

#3


0  

use replace

x='Hello what is up. ^M\
^M\
What are you doing?'

print x.replace('^M','') # the second parameter  insert what you want replace it with 

#1


7  

''.join(somestring.split(r'\r'))

or

somestring.replace(r'\r','')

This assumes you have carriage return characters in your string, and not the literal "^M". If it is the literal string "^M" then substiture r'\r' with "^M"

假设您的字符串中有回车符,而不是文字“^ M”。如果它是文字字符串“^ M”那么替换r'\ r'和“^ M”

If you want the newlines gone then use r'\r\n'

如果你想要换行,那就用r'\ r \ n'

This is very basic string manipulation in python and it is probably worth looking at some basic tutorials http://mihirknows.blogspot.com.au/2008/05/string-manipulation-in-python.html

这是python中非常基本的字符串操作,可能值得查看一些基本的教程http://mihirknows.blogspot.com.au/2008/05/string-manipulation-in-python.html

And as the first commenter said its always helpful to give some indication of what you have tried so far, and what you don't understand about the problem, rather than asking for an straight answer.

正如第一位评论者所说,它总是有助于给出你到目前为止所尝试的内容的一些指示,以及你对这个问题不了解的内容,而不是直截了当地回答问题。

#2


6  

Try:

>>> mystring = mystring.replace("\r", "").replace("\n", "")

(where "mystring" contain your text)

(“mystring”包含你的文字)

#3


0  

use replace

x='Hello what is up. ^M\
^M\
What are you doing?'

print x.replace('^M','') # the second parameter  insert what you want replace it with