使用 unicode 字符 u201c

Dav*_*d Q 5 python unicode encoding utf-8 python-3.x

我是 python 的新手,在理解 unicode 时遇到问题。我正在使用 Python 3.4。我花了一整天试图通过阅读有关 unicode 的信息来解决这个问题,包括http://www.fileformat.info/info/unicode/char/201C/index.htmhttp://python-notes.curiousefficiency.org /en/latest/python3/text_file_processing.html

我需要引用特殊引号,因为它们用于我正在分析的文本中。我确实测试过 W7 命令窗口可以读写 2 个特殊引号字符。为了简单起见,我写了一个单行脚本:

print ('“') # that's the special quote mark in between normal single quotes
Run Code Online (Sandbox Code Playgroud)

并得到这个输出:

Traceback (most recent call last):
  File "C:\Users\David\Documents\Python34\Scripts\wordCount3.py", line 1, in <module>
    print ('\u201c')
  File "C:\Python34\lib\encodings\cp437.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u201c' in position 0: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)

那么我如何写一些东西来引用这两个字符u201Cu201D

这是文件打开语句中的正确编码选择吗?

with open(fileIn, mode='r', encoding='utf-8', errors='replace') as f:
Run Code Online (Sandbox Code Playgroud)

tho*_*nev 2

原因是在 3.x Python 中你不能将 unicode 字符串与字节字符串混合在一起。也许,您已经阅读了有关 Python 2.x 的手册,只要字节串包含可转换字符,这些事情都是可能的。

print('\u201c', '\u201d')
Run Code Online (Sandbox Code Playgroud)

对我来说效果很好,所以唯一的原因是您对源文件或终端使用了错误的编码。

另外,您可以通过在源代码之上添加下一行来明确将 python 指向您正在使用的代码页:

 # -*- coding: utf-8 -*-
Run Code Online (Sandbox Code Playgroud)

添加:看来您正在 Windows 计算机上工作,如果是这样,您可以通过运行将控制台代码页更改为 utf-8

chcp 65001
Run Code Online (Sandbox Code Playgroud)

在启动 python 解释器之前。该更改将是临时的,如果您想要永久更改,请运行下一个 .reg 文件:

Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Console]
"CodePage"=dword:fde9
Run Code Online (Sandbox Code Playgroud)