-1

我想将一个字符串保存到一个新的 txt 文件中。

字符串的编码是'utf-8'(我想是这样),它包含一些汉字

但文件是GB2312

这是我的代码,我省略了一些:

# -*- coding:utf-8 -*-
# Python 3.4 window 7

def getUrl(self, url, coding='utf-8'):
    self.__reCompile = {}
    req = request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 UBrowser/5.5.9703.2 Safari/537.36')
    with request.urlopen(req) as response:
        return response.read().decode(coding)

def saveText(self,filename,content,mode='w'):
    self._checkPath(filename)
    with open(filename,mode) as f:
        f.write(content)

joke= self.getUrl(pageUrl)
#some re transform such as re.sub('<br>','\r\n',joke)
self.saveText(filepath+'.txt',joke,'a')

有时会出现 UnicodeEncodeError: 在此处输入图像描述

4

3 回答 3

4

您的异常在“saveText”中引发,但我看不到您是如何实现它的,因此我将尝试重现该错误并提出修复建议。

在 'getUrl' 中,您返回一个解码的字符串( .decode('utf-8') ),我的猜测是,在 'saveText' 中,您忘记在写入文件之前对其进行编码。

重现错误

试图重现错误,我这样做了:

# String with unicode chars, decoded like in you example
s = 'æøå'.decode('utf-8') 

# How saveText could be:
# Encode before write
f = open('test', mode='w')
f.write(s)
f.close()

这给出了一个类似的例外:

---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-36-1309da3ad975> in <module>()
      5 # Encode before write
      6 f = open('test', mode='w')
----> 7 f.write(s)
      8 f.close()

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

两种固定方式

您可以执行以下任一操作:

# String with unicode chars, decoded like in you example
s = 'æøå'.decode('utf-8') 

# How saveText could be:
# Encode before write
f = open('test', mode='w')
f.write(s.encode('utf-8'))
f.close()

或者您可以尝试使用模块“编解码器”编写文件:

import codecs

# String with unicode chars, decoded like in you example
s = 'æøå'.decode('utf-8') 

# How saveText could be:
f = codecs.open('test', encoding='utf-8', mode='w')
f.write(s)  
f.close()

希望这可以帮助。

于 2016-01-14T11:28:16.213 回答
2

字符串的编码是'utf-8'(我想是这样),它包含一些汉字

您已经使用 UTF-8 解码了来自远程服务器的响应。一旦它被解码为 Python 字符串,它就不再被编码并有效地存储为内存中的Unicode 点

您收到的错误是因为 Python 正在尝试使用您的代码页将字符串转换为字节。由于您的 Windows 区域设置,它选择了 GBK,它不支持所有 Unicode 字符。

要保存,您只需使用(Python 3. 在 Python 2 中,使用) 的encoding参数以指定的编码打开输出文件。在您的情况下,“UTF-8”可能是适合使用的编码。open()io.open()

您的saveText()方法需要更新为:

def saveText(self,filename,content,mode='w',encoding="utf-8"):
    self._checkPath(filename)
    with open(filename,mode,encoding) as f:
        f.write(content)

您的 HTTP 数据可能会遇到问题。您在解码响应时假设远程内容是 UTF-8。情况并非总是如此。您可以分析 HTTP 响应标头以获取正确的编码或使用Requests库,它会为您执行此操作。您的 URL getter 如下所示:

def getUrl(url):
    headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 UBrowser/5.5.9703.2 Safari/537.36'}
    response = requests.get(url, headers=headers)
    response.raise_for_status() # Throw an exception on errors
    return response.text
于 2016-01-15T11:38:24.607 回答
1

我认为您的终端使用的编码不支持该字符。Python 处理得很好,我认为是您的输出编码无法处理它。

另请参阅此问题

于 2016-01-14T10:53:01.690 回答