Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.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 将HTML实体解码为Unicode_Python_Unicode_Character Encoding - Fatal编程技术网

Python 将HTML实体解码为Unicode

Python 将HTML实体解码为Unicode,python,unicode,character-encoding,Python,Unicode,Character Encoding,嗯,从昨天起我就有麻烦了。我需要将一些文本保存到一个“.txt”文件中,问题是我试图保存的文本中有html实体 因此,我在代码中导入了HTMLPaser: import HTMLParser h = HTMLParser.HTMLParser() print h.unescape(text) // right? 问题是,当你试图打印结果时,这是可行的,但我试图将其返回到我的函数中,该函数实际上将文本保存到文件中。因此,当我试图保存文件时,系统会说: exceptions.UnicodeEnc

嗯,从昨天起我就有麻烦了。我需要将一些文本保存到一个“.txt”文件中,问题是我试图保存的文本中有html实体

因此,我在代码中导入了HTMLPaser:

import HTMLParser
h = HTMLParser.HTMLParser()
print h.unescape(text) // right? 
问题是,当你试图打印结果时,这是可行的,但我试图将其返回到我的函数中,该函数实际上将文本保存到文件中。因此,当我试图保存文件时,系统会说:

exceptions.UnicodeEncodeError: 'ascii' codec can't encode character u'\xab' in position 0: ordinal not in range(128)
我一直在读这方面的文章,但我不能得出任何结论,我尝试了BeautifulSoup,我尝试了著名的pythonists函数,但都没有成功。你能帮我吗?我需要将文件中的文本保存为unicode,通过unicode,我知道它将保存以下字符:á,对吗?

“将unicode字符保存到文件”与“将HTML实体解码为unicode”是不同的问题。您的代码(
h.unescape(text)
)已正确解码html文本

例外情况是由于
打印unicode\u文本
造成的,例如:

print u"\N{EURO SIGN}"
应该会产生类似的错误

如果要通过重定向python脚本的输出保存到文件,例如:

$ python -m your_module >output.txt #XXX raises an error for non-ascii data
然后定义
pythonionecoding=utf-8
envvar(使用utf-8编码保存):

如果要直接在Python代码中保存到文件,请使用
io
模块:

import io

with io.open(filename, 'w', encoding='utf-8') as file:
    file.write(h.unescape(text))

你能告诉我们写文件的代码吗?听起来问题其实在于编写文件而不是读取html(因为您在使用print测试它时说这是可行的)/
import io

with io.open(filename, 'w', encoding='utf-8') as file:
    file.write(h.unescape(text))