我有一個從RST源使用斯芬克斯生成的TEX文件時,它被編碼爲UTF-8無BOM(根據記事本++)並命名爲final_report.tex
,具有以下內容:的Python line.replace返回UnicodeEncodeError
% 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}')
這工作在Ubuntu 16.04使用Python 2.7,以及Python的3.5, 但它在Windows上無法與Python 3.4。 錯誤消息我得到的是:
其中201c
代表左雙引號。如果我刪除有問題的角色,則腳本繼續進行,直到找到下一個有問題的角色。最後,我需要一個可以在Python和Windows上運行Python 2.7和3.x的解決方案。我嘗試了很多建議在這裏對這樣的解決方案,而不是仍可能找到一個對我的作品......
嗨@matth你是什麼在第19行? –
我的例子沒有19行,我假設錯誤信息引用了'cp850.py'文件的第19行。 – matth
相關:http://stackoverflow.com/questions/10971033/backporting-python-3-openencoding-utf-8-to-python-2 – matth