【问题标题】:Python 3.6 utf-8 UnicodeEncodeErrorPython 3.6 utf-8 UnicodeEncodeError
【发布时间】:2018-10-02 09:52:49
【问题描述】:
#!/usr/bin/env python3
import glob
import xml.etree.ElementTree as ET
filenames = glob.glob("C:\\Users\\####\\Desktop\\BNC2\\[A00-ZZZ]*.xml")
out_lines = []
for filename in filenames:
    with open(filename, 'r', encoding="utf-8") as content:
        tree = ET.parse(content)
        root = tree.getroot()
        for w in root.iter('w'):
            lemma = w.get('hw')
            pos = w.get('pos')
            tag = w.get('c5')

            out_lines.append(w.text + "," + lemma + "," + pos + "," + tag)

with open("C:\\Users\\####\\Desktop\\bnc.txt", "w") as out_file:
    for line in out_lines:
        line = bytes(line, 'utf-8').decode('utf-8', 'ignore')
        out_file.write("{}\n".format(line))

给出错误:

UnicodeEncodeError:“charmap”编解码器无法在位置 0 编码字符“\u2192”:字符映射到未定义

我以为这条线会解决这个问题...

line = bytes(line, 'utf-8').decode('utf-8', 'ignore')

【问题讨论】:

  • 你试过open("C:\\Users\\####\\Desktop\\bnc.txt", "w", encoding='utf8')吗??
  • 请发布整个回溯。 Python 告诉你哪条线路有问题... 向前支付!不要让我们猜测。
  • line = bytes(line, 'utf-8').decode('utf-8', 'ignore') 所做的只是编码为 utf-8 并再次解码。你得到原来的字符串。我怀疑的问题是当您尝试写入 ascii 文件时。

标签: python unicode utf-8


【解决方案1】:

你需要在打开输出文件时指定编码,就像你打开输入文件一样:

with open("C:\\Users\\####\\Desktop\\bnc.txt", "w", encoding="utf-8") as out_file:
    for line in out_lines:
        out_file.write("{}\n".format(line))

【讨论】:

  • @Ry,完美。如此简单,但有效。谢谢!
【解决方案2】:

如果您的脚本有多个读取和写入,并且您希望所有这些都具有特定的编码(比如说 utf-8),我们也可以更改默认编码

import sys
reload(sys)
sys.setdefaultencoding('UTF8')

我们应该只在我们有多个读/写时才使用它,并且应该在脚本的开头完成

Changing default encoding of Python?

【讨论】:

  • 这不起作用。 (stackoverflow.com/questions/3828723/…)。太糟糕了,setdefaultencoding 已经消失了。除非你做一些 hacky 的东西,否则你不会在 3.6 中找到它。
  • 是的,但是当我必须阅读时,我有时会使用它。虽然没有用 Python 3.6 尝试过
  • 更改默认值是错误的。它破坏了其他期望默认为“默认”的模块。这就是为什么除非您执行重新加载“技巧”,否则该功能不起作用。只需使用正确的编码打开文件!
猜你喜欢
  • 2017-07-27
  • 2017-06-05
  • 2018-06-29
  • 2015-03-03
  • 1970-01-01
  • 2015-02-06
  • 1970-01-01
  • 1970-01-01
  • 2017-05-07
相关资源
最近更新 更多