将python脚本输出输出到文件时出现Unicode错误

Kai*_*eks 17 python unicode beautifulsoup

这是代码:

print '"' + title.decode('utf-8', errors='ignore') + '",' \
      ' "' + title.decode('utf-8', errors='ignore') + '", ' \
      '"' + desc.decode('utf-8', errors='ignore') + '")'
Run Code Online (Sandbox Code Playgroud)

标题和desc由Beautiful Soup 3(p [0] .textp [0] .prettify)返回,据我所知,BeautifulSoup3文档是UTF-8编码的.

如果我跑

python.exe script.py > out.txt
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Traceback (most recent call last):
  File "script.py", line 70, in <module>
    '"' + desc.decode('utf-8', errors='ignore') + '")'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 264
: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

但是,如果我跑

python.exe script.py
Run Code Online (Sandbox Code Playgroud)

我没有错.仅在指定输出文件时才会发生.

如何在输出文件中获得良好的UTF-8数据?

Mak*_*cha 12

您可以使用编解码器模块将unicode数据写入文件

import codecs
file = codecs.open("out.txt", "w", "utf-8")
file.write(something)
Run Code Online (Sandbox Code Playgroud)

'print'输出到标准输出,如果你的控制台不支持utf-8,即使你将stdout传输到文件也会导致这样的错误.


Jir*_*iri 7

在这种情况下,Windows行为有点复杂.您应该听取其他建议,并在输入过程中内部使用unicode进行字符串和解码.

对于你的问题,你需要打印编码的字符串(只有你知道哪个编码!)在stdout重定向的情况下,但你必须在简单的屏幕输出(和python或Windows控制台处理转换为正确的编码)的情况下打印unicode字符串.

我建议用这种方式构建脚本:

# -*- coding: utf-8 -*- 
import sys, codecs
# set up output encoding
if not sys.stdout.isatty():
    # here you can set encoding for your 'out.txt' file
    sys.stdout = codecs.getwriter('utf8')(sys.stdout)

# next, you will print all strings in unicode
print u"Unicode string ?š??žý"
Run Code Online (Sandbox Code Playgroud)

更新:另请参阅其他类似问题:在Python中管道stdout时设置正确的编码