【问题标题】:Python line.replace returns UnicodeEncodeErrorPython line.replace 返回 UnicodeEncodeError
【发布时间】:2016-11-06 07:28:48
【问题描述】:

我有一个使用 Sphinx 从 rst 源生成的 tex 文件,它被编码为没有 BOM 的 UTF-8(根据 Notepad++)并命名为final_report.tex,内容如下:

% Generated by Sphinx.
\documentclass[letterpaper,11pt,english]{sphinxmanual}
\usepackage[utf8]{inputenc}
\begin{document}

\chapter{Preface}
Krimson4 is a nice programming language.
Some umlauts äöüßÅö.
That is an “double quotation mark” problem.
Johnny’s apostrophe allows connecting multiple ports.
Components that include data that describe how they ellipsis …
Software interoperability – some dash – is not ok.
\end{document}

现在,在我将 tex 源代码编译为 pdf 之前,我想替换 tex 文件中的一些行以获得更好的结果。我的脚本灵感来自another SO question

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os

newFil=os.path.join("build", "latex", "final_report.tex-new")
oldFil=os.path.join("build", "latex", "final_report.tex")

def freplace(old, new):
    with open(newFil, "wt", encoding="utf-8") as fout:
        with open(oldFil, "rt", encoding="utf-8") as fin:
            for line in fin:
                print(line)
                fout.write(line.replace(old, new))
    os.remove(oldFil)
    os.rename(newFil, oldFil)

freplace('\documentclass[letterpaper,11pt,english]{sphinxmanual}', '\documentclass[letterpaper, 11pt, english]{book}') 

这适用于带有 Python 2.7 和 Python 3.5 的 Ubuntu 16.04, 但它在使用 Python 3.4 的 Windows 上失败。 我得到的错误信息是:

File "C:\Python34\lib\encodings\cp850.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u201c' in position 11: character maps to <undefined>

其中201c 代表左双引号。如果我删除有问题的字符,脚本会继续执行,直到找到下一个有问题的字符。

最后,我需要一个在 Linux 和 Windows 上使用 Python 2.7 和 3.x 的解决方案。我在 SO 上尝试了很多这里建议的解决方案,但还没有找到适合我的解决方案......

【问题讨论】:

标签: python python-unicode


【解决方案1】:

您需要使用encoding="the_encoding" 指定正确的编码:

with open(oldFil, "rt", encoding="utf-8") as fin,  open(newFil, "wt", encoding="utf-8") as fout:

如果您不这样做,将使用首选编码。

open

在文本模式下,如果未指定编码,则使用的编码取决于平台:调用 locale.getpreferredencoding(False) 以获取当前的语言环境编码

【讨论】:

  • @matth,什么双引号?如果您仍然有编码问题,那么您没有 utf-8 编码数据
  • @matth,您已将两者的编码指定为 utf-8,并且错误发生在写入时?
  • @matth,所以设置编码修复了第一个错误,但现在你有另一个错误?
  • 对于 python 2,您需要使用 io lib,使用 io.open。当我今晚回到我的比赛时,我将添加一个指向一个不错的答案的链接,该答案允许您从 cmd shell 打印,尽管我建议使用 cygwin 作为 Windows 上的默认 shell 或使用像 pycharm 这样的一面。
  • 不需要,Python3 的 open 是 io.open 所以代码在 2.7 和 3 中都可以正常工作
猜你喜欢
  • 2020-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-03
  • 2017-12-23
  • 2012-11-06
  • 1970-01-01
相关资源
最近更新 更多