2016-07-04 34 views
2

我有一个从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的解决方案。我尝试了很多建议在这里对这样的解决方案,而不是仍可能找到一个对我的作品......

+0

嗨@matth你是什么在第19行? –

+0

我的例子没有19行,我假设错误信息引用了'cp850.py'文件的第19行。 – matth

+0

相关:http://stackoverflow.com/questions/10971033/backporting-python-3-openencoding-utf-8-to-python-2 – matth

回答

2

您需要指定正确的编码与encoding="the_encoding"

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

如果您不要使用首选编码。

open

在文本模式下,如果编码未指定使用的编码依赖于平台:是locale.getpreferredencoding(假)被调用来获得当前本地编码

+0

@matth,什么双引号?如果你仍然有编码问题,那么你没有utf-8编码数据 –

+0

什么是确切的新错误? –

+0

@matth,你指定编码为utf-8,并且在写入时发生错误? –