2016-07-04 27 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,並且在寫入時發生錯誤? –