如何用现有的unicode字符转换字符串类型?

2024-09-30 01:21:27 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python2.7,我有一个端点,它返回包含字符“\u2019”、“\u2018”和“\u2026”的字符串。我还不能用任何编码、解码等组合来解决这些问题

实际字符串如下所示: “\u2018Ralph打破了互联网,2018年信条II是感恩节的热门歌曲”

这是一个代码片段

#!/usr/bin/python
# -*- coding: utf-8 -*-
...
>>> '\u2019'.encode('ascii')
'\\u2019'
>>> '\u2019'.encode('utf-8')
'\\u2019'
>>> '\u2019'.decode('utf-8')
u'\\u2019'
>>>'\u2019'.decode('ascii')
u'\\u2019'

我正在运行命令行,但也曾试图输出到文件,但没有用。在这类问题上有很多类似的线索,但是还没有找到一个能解决这个问题的。我想我可以做一些正则表达式字符查找和替换,但这看起来很笨拙。在


Tags: 字符串编码ascii互联网解码端点字符utf
3条回答

我已经投了@Ying Cai的票,但我会给你一些提示: 如果在使用Python 2.7时添加from __future__ import unicode_literals,则整个文件将被视为Python 3.X,这意味着所有字符串文本都将被视为unicode。如果您在Python 2.7上,并且使用u"\u2018Ralph Breaks the Internet\u2019 and \u2018Creed II\u2019 Are Thanksgiving Hits"而不添加from __future__ import unicode_literals,则字符串现在是{},它应该可以像您预期的那样工作。在

@Mark我刚刚更新了我的答案,因为我真的在想from __future__ import unicode_literals,而不是{}。谢谢你的评论。在

你检查过这个线程了吗:Removing \u2018 and \u2019 character

这些是引号字符的Unicode。在

u"\u2018Ralph Breaks the Internet\u2019 and \u2018Creed II\u2019 Are Thanksgiving Hits"

返回:
《拉尔夫打破互联网》和《信条2》是感恩节的热门歌曲

希望这有帮助。在

在Python2上打印非ASCII字符需要3件事。在

  • 使用print
  • 终端编码必须支持字符。在
  • 字体必须支持以下字符:

示例(使用代码页437的Windows控制台):

C:\>py -2
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> u'\u2018Ralph\u2019'     # Didn't use `print`
u'\u2018Ralph\u2019'
>>> print u'\u2018Ralph\u2019'  # cp437 doesn't support these characters.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u2018' in position 0: character maps to <undefined>
>>> ^Z

将代码页更改为支持以下字符的代码页:

^{pr2}$

请注意,最新的python3的工作方式不同。代码页无关紧要(但字体重要):

C:\>py -3
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> '\u2018Ralph\u2019'
'‘Ralph’'
>>> print('\u2018Ralph\u2019')
‘Ralph’
>>> print(ascii('\u2018Ralph\u2019'))  # Old behavior to see escape codes.
'\u2018Ralph\u2019'

相关问题 更多 >

    热门问题