在Python3.2中运行这个UTF-8编码的脚本有一个奇怪的问题。如果Python包含日语平假名字符の(参见下面的堆栈跟踪),它将拒绝运行
Traceback (most recent call last):
File "MyScript.py", line 20, in <module>
print(no)
File "C:\Python32\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u306e'
in position 0: character maps to <undefined>
它在没有这一个字符的情况下运行得很好(文件中还有其他字符),我不知道为什么。任何帮助都将不胜感激。
下面是一个为我重现错误的脚本:
#!/usr/bin/env python
# coding=utf-8
import glob
import codecs
import os.path
from datetime import datetime, timedelta
assTemplate = \
r"""タイトル\N {time.year}年{time.month}月{time.day}日 {age}\N{place}"""
for mtsName in glob.glob('./*.MTS'):
baseName = mtsName.lower().replace('.mts', '')
mtsName = os.path.abspath(mtsName)
# Get the time the video file was created.
mtsTimestamp = datetime.fromtimestamp(os.stat(mtsName).st_ctime)
no = '\u306e'
print(no) ## UnicodeDecodeError
age = '生後'
place = '自宅'
print('自宅')
# Generate the contents of the ASS file.
assContents = assTemplate.format(time=mtsTimestamp, age=age, place=place)
# Write the ASS file.
print(assContents)
之所以使用Python3.2,是因为在Python2.7.2中,使用unicode字符串进行字符串格式化对我来说根本不起作用。
发布于 2011-08-21 02:39:28
您正尝试将unicode字符打印到使用cp1252的终端。cp1525根本不支持任何日语字符。因此,该字符不是问题,我敢打赌,对于任何日语字符,您都会得到完全相同的错误。
发布于 2012-01-21 13:43:39
我也有这个问题。我的语言是越南语。您可以剪切文件cp1252.py或删除此文件。您应该剪切此文件并移动另一个文件夹,任何您喜欢的文件夹。现在,在encodings文件夹中没有cp1252.py文件,不用担心。接下来,复制encodings文件夹中的utf-8文件,并将该文件粘贴到encodings文件夹中,然后将该文件重命名为cp1252.py。你明白吗。
我像那样解决了这个问题。
祝你成功!
我在雅虎的昵称是: phong_ux。如果你需要更多的帮助,我很乐意帮助你。
https://stackoverflow.com/questions/7133572
复制相似问题