Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 替换特殊字符(\n、\r等)_Python - Fatal编程技术网

Python 替换特殊字符(\n、\r等)

Python 替换特殊字符(\n、\r等),python,Python,我有html源代码,我从网站上获得,使用: from urllib.request import urlopen url = 'http://...' html = str(urlopen(url).read()) 然后我将其保存在一个文件中,操作如下: with open('/file/path', 'w') as f: f.write(html) 执行此操作时,源代码中的新行将替换为'\r\n'。 我想知道如何删除这些字符或用它们的含义(换行、制表符等)替换它们 我试图使用htm

我有html源代码,我从网站上获得,使用:

from urllib.request import urlopen
url = 'http://...'
html = str(urlopen(url).read())
然后我将其保存在一个文件中,操作如下:

with open('/file/path', 'w') as f:
    f.write(html)
执行此操作时,源代码中的新行将替换为
'\r\n'
。 我想知道如何删除这些字符或用它们的含义(换行、制表符等)替换它们


我试图使用
html.replace('\r\n','\n')
,但它不起作用。

我认为您将
replace
视为直接修改字符串的内容,而不是返回需要分配给新变量的内容

from urllib.request import urlopen
url = 'http://www.google.com'
html = str(urlopen(url).read())

html_2 = html.replace('\r','')

with open('/file/path/filename.txt', 'w') as f:
    f.write(html_2)
http.client.HTTPResponse上的
read()。您不能简单地使用
str(您的\r\n字节\u对象)
将其转换为
\r\n
(打印为换行符)转换为
\\r\\n
(实际打印为
\r\n
而不是换行符的编码形式):

相反,您必须使用
bytes.decode(您的_编码)
对给定的
bytes
对象进行解码
latin-1
通常用作编码,如果您只需要将其解码为字符串以写入文件:

>>> a_bytes_object.decode("latin-1")
'This is a test\r\nMore test'
>>> print(a_bytes_object.decode("latin-1"))
This is a test
More test
您也可以将编码作为第二个参数传递给
str
,而不是使用
decode
str(一个字节对象,“拉丁语-1”)
而不是
a\u字节\u对象。解码(“拉丁语-1”)

或者,您可以简单地以二进制模式打开文件(
open('/file/path',wb')
)并将bytes对象写入其中

with open('/file/path', 'wb') as f:
    f.write(html)

您也可以尝试读取
内容类型
标题(类似于
text/html;charset=ISO-8859-1
)来提取字符集,然后解码为正确的字符串,但这是有风险的,因为它并不总是有效(并非所有服务器都发送标题,并非所有服务器都包含编码,并非所有编码都受Python支持,等等).

你是想写
html.replace('\r\n','\n')
?你在哪个平台上?还是只写
html.replace('\r','')
html.translate(无,'\r')
;-)是的,谢谢,但是f.replace('\r\n','')不起作用。不,不,不要调用
f.replace
。尝试
html。替换
with open('/file/path', 'wb') as f:
    f.write(html)