unicode,而不是 python 中的 str

use*_*er1 1 python python-2.7

我试图运行这个 Python 代码:

with io.open(outfile, 'w' ) as processed_text, io.open(infile, 'r') as fin:
    for line in fin:
        processed_text.write(preprocess(line.rstrip())+'\n')
Run Code Online (Sandbox Code Playgroud)

但得到 TypeError: must be unicode, not str

我怎么解决这个问题?我在这里搜索了类似的问题,并找到了一个可以尝试的问题

with io.open(outfile, 'w', encoding="utf-8") as processed_text, io.open(infile, 'r') as fin:
Run Code Online (Sandbox Code Playgroud)

但没有用。

tvt*_*173 5

尝试将其放在文件的最顶部:

from __future__ import unicode_literals
Run Code Online (Sandbox Code Playgroud)

Python 3.x 默认使用 unicode。这将导致 Python 2.x 遵循相同的行为。

如果您仍然有问题,您可以手动转换问题字符串 ala

uni_string = unicode(my_string)
Run Code Online (Sandbox Code Playgroud)