【发布时间】: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 上尝试了很多这里建议的解决方案,但还没有找到适合我的解决方案......
【问题讨论】:
-
嗨@matth 你在第 19 行有什么?
-
我的示例没有 19 行,我假设错误消息是指
cp850.py文件的第 19 行。
标签: python python-unicode