标签: python-unicode

如何在 python 2 和 3 中使用 unicode_literals 获得兼容的 type() 行为?

这个问题看起来与这个问题非常相似,但是评论中的建议不起作用(不再?),如下所示。

我正在尝试编写一个 python2-3 兼容包,我的方法之一有一个类生成器,并且type()在 python-2.7 测试中给我带来了问题:

Python 2.7.13 (default, Mar 18 2017, 17:03:32) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import unicode_literals
>>> from builtins import str
>>> type('MyClass', (object,), {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() argument 1 must be string, not unicode
>>> type(str('MyClass'), (object,), {})
Traceback (most recent call last):
  File "<stdin>", …
Run Code Online (Sandbox Code Playgroud)

python python-2.7 python-unicode python-3.6

3
推荐指数
1
解决办法
2018
查看次数

Python字典键/带前缀的值 - 前缀是什么?

我最近看到一个Python dict看起来像这样:

test1 = {u'user':u'user1', u'user_name':u'alice'}
Run Code Online (Sandbox Code Playgroud)

这让我感到困惑,u键/值对之前是什么?它是某种前缀吗?这有什么不同:

test2 = {'user':'user1', 'user_name':'alice'}
Run Code Online (Sandbox Code Playgroud)

我试过玩test1和test2; 他们似乎没有什么不同.有人可以解释前缀的用途吗?

>>> test1 = {u'user':u'user1', u'user_name':u'alice'}
>>> test2 = {'user':'user1', 'user_name':'alice'} 
>>> print test1[u'user']
user1
>>> print test1['user']
user1
>>> print test2['user']
user1
>>> print test2[u'user']
Run Code Online (Sandbox Code Playgroud)

python unicode python-unicode

2
推荐指数
1
解决办法
2199
查看次数

Python UnicodeEncodeError

我试图用这个语句将一些数据插入到MySQL数据库中:

INSERT INTO tweets(tweeter,tweet)VALUES ('Lord_Sugar','RT @BTSport: This cerebral figure succeeds in insulting everyone’s intelligence. @CalvinBook looks at Kinnears impact on #NUFC http://t.…')
Run Code Online (Sandbox Code Playgroud)

但是我收到了这个错误:

UnicodeEncodeError: 'latin-1' codec can't encode character u'\u2019' in position 119: ordinal not in range(256)
Run Code Online (Sandbox Code Playgroud)

我知道它在谈论哪个角色 - 它在推文末尾的'...',但不知道如何绕过它.

python mysql database python-2.7 python-unicode

2
推荐指数
1
解决办法
1054
查看次数

我应该如何将包含unicode字符的字符串转换为unicode?

我认为我主宰了Python 2中的所有Unicode内容,但似乎有些东西我不明白.我有来自HTML的用户输入到我的python脚本:

a = "m\xe9dico"
Run Code Online (Sandbox Code Playgroud)

我希望这是médico(这意味着医生).所以要将其转换为unicode我正在做:

a.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)

要么:

unicode(a, "utf-8")
Run Code Online (Sandbox Code Playgroud)

但这是投掷:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128) 
Run Code Online (Sandbox Code Playgroud)

怎么能实现这个?

python unicode python-2.7 python-unicode

2
推荐指数
1
解决办法
124
查看次数

从文件读取utf-8转义序列

我有一个utf-8编码的文件,其中包含多行,例如

\ x02我不喜欢\ x0307香蕉\ x03。\ x02
嗨,你好吗?
你打过电话了?

如何将文件的行读取到列表中,对所有转义序列进行解码?我尝试了下面的代码:

with codecs.open(file, 'r', encoding='utf-8') as q:
    quotes = q.readlines()

print(str(random.choice(quotes)))
Run Code Online (Sandbox Code Playgroud)

但是它打印行而不解码转义字符。

\ x02我不喜欢\ x0307香蕉\ x03 \ x02

(请注意:转义字符是IRC颜色代码,\x02是加粗文本的字符,并且\x03是颜色代码的前缀。此外,此代码来自我的IRC僵尸程序,其中的MSG功能由代替print())

python utf8-decode python-unicode

2
推荐指数
1
解决办法
2708
查看次数

在Python 3中显示Unicode符号的文本表示

我可以在我的ipython笔记本中做到这一点:

print(u"\u2605")
Run Code Online (Sandbox Code Playgroud)

★

但是我该如何倒退呢?也就是说,从符号转到unicode字符串.以UTF-8或UTF-16编码它给出了二进制表示.例如:

print('?'.encode('utf-16'))
Run Code Online (Sandbox Code Playgroud)

B '\ XFF\XFE\X05&'

python unicode python-3.x emoji python-unicode

2
推荐指数
1
解决办法
120
查看次数

python3 UnicodeEncodeError:'charmap'编解码器不能编码位置95-98中的字符:字符映射到<undefined>

一个月前我遇到了这个Github:https://github.com/taraslayshchuk/es2csv

我在Linux ubuntu中通过pip3安装了这个软件包.当我想使用这个包时,我遇到了这个包适用于python2的问题.我深入研究了代码,很快就发现了问题.

                for line in open(self.tmp_file, 'r'):
                timer += 1
                bar.update(timer)
                line_as_dict = json.loads(line)
                line_dict_utf8 = {k: v.encode('utf8') if isinstance(v, unicode) else v for k, v in line_as_dict.items()}
                csv_writer.writerow(line_dict_utf8)
            output_file.close()
            bar.finish()
        else:
            print('There is no docs with selected field(s): %s.' % ','.join(self.opts.fields))
Run Code Online (Sandbox Code Playgroud)

代码检查了unicode,这在python3中是不必要的.因此,我将代码更改为下面的代码.因此,该软件包在Ubuntu 16下正常运行.

                for line in open(self.tmp_file, 'r'):
                timer += 1
                bar.update(timer)
                line_as_dict = json.loads(line)
                # line_dict_utf8 = {k: v.encode('utf8') if isinstance(v, unicode) else v for k, v in line_as_dict.items()}
                csv_writer.writerow(line_as_dict)
            output_file.close()
            bar.finish()
        else:
            print('There …
Run Code Online (Sandbox Code Playgroud)

python-3.x python-unicode elasticsearch-plugin

2
推荐指数
1
解决办法
2万
查看次数

尝试使用pdfminer.six提取文本时如何解决“ UnicodeDecodeError”?

通过以下方式使用pdfminer(git的最新版本)安装时,出现UnicodeEncodeError pip install git+https://github.com/pdfminer/pdfminer.six.git:

Traceback (most recent call last):
  File "pdfminer_sample3.py", line 34, in <module>
    print(convert_pdf_to_txt("samples/numbers-test-document.pdf"))
  File "pdfminer_sample3.py", line 27, in convert_pdf_to_txt
    text = retstr.getvalue()
  File "/usr/lib/python2.7/StringIO.py", line 271, in getvalue
    self.buf += ''.join(self.buflist)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

脚本

#!/usr/bin/env python

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from StringIO import StringIO
import codecs …
Run Code Online (Sandbox Code Playgroud)

python pdf python-unicode pdfminer

2
推荐指数
1
解决办法
741
查看次数

如何正确迭代 Python 中的 unicode 字符

我想遍历一个字符串并输出所有表情符号。

我正在尝试遍历字符,并根据表情符号列表检查它们。

但是,python 似乎将 unicode 字符拆分为较小的字符,从而破坏了我的代码。例子:

>>> list(u'Test \U0001f60d')
[u'T', u'e', u's', u't', u' ', u'\ud83d', u'\ude0d']
Run Code Online (Sandbox Code Playgroud)

有什么想法为什么 u'\U0001f60d' 会分裂?

或者有什么更好的方法来提取所有表情符号?这是我的原始提取代码:

def get_emojis(text):
  emojis = []
  for character in text:
    if character in EMOJI_SET:
      emojis.append(character)
  return emojis
Run Code Online (Sandbox Code Playgroud)

python unicode python-unicode

2
推荐指数
1
解决办法
1974
查看次数

使用UTF-8编码字符打印字符串,例如:"\ u00c5\u009b \"

我想打印像这样编码的字符串:"Cze\u00c5\u009b\u00c4\u0087"但我不知道怎么做.示例字符串应打印为:"Cześć".

我试过的是:

str = "Cze\u00c5\u009b\u00c4\u0087"
print(str) 
#gives: CzeÅÄ

str_bytes = str.encode("unicode_escape")
print(str_bytes) 
#gives: b'Cze\\xc5\\x9b\\xc4\\x87'

str = str_bytes.decode("utf8")
print(str) 
#gives: Cze\xc5\x9b\xc4\x87
Run Code Online (Sandbox Code Playgroud)

哪里

print(b"Cze\xc5\x9b\xc4\x87".decode("utf8"))
Run Code Online (Sandbox Code Playgroud)

给出"Cześć",但我不知道如何将"Cze\xc5\x9b\xc4\x87"字符串转换为b"Cze\xc5\x9b\xc4\x87"字节.

我也知道在使用"unicode_escape"参数编码基础字符串后,问题是字节表示中的额外反斜杠,但我不知道如何摆脱它们 - str_bytes.replace(b'\\\\', b'\\')不起作用.

python python-3.x python-unicode

2
推荐指数
1
解决办法
244
查看次数