首页 > python如何逐个字符来遍历,其中将汉字和英文字符看成等同的?

python如何逐个字符来遍历,其中将汉字和英文字符看成等同的?

举例来说:str="图片picture",遍历的时候的结果应该是‘图’,‘片’,‘p’,‘i’,‘c’,‘t’,‘u’,‘r’,‘e’,


python新手。
chardet.detect测下当前编码,再用str.decode解码:
一段交互:

>>> s = "图片picture"
>>> import chardet
>>> chardet.detect(s)
{'confidence': 0.7525, 'encoding': 'utf-8'}
>>> for c in s.decode('utf-8'):
...     print c
... 
图
片
p
i
c
t
u
r
e

两个调用合到一行:

for c in s.decode(chardet.detect(s)['encoding']):
    print c

参考:
https://pypi.python.org/pypi/chardet
http://tool.oschina.net/uploads/apidocs/python2.7.3/library/stdtypes.h...

【热门文章】
【热门文章】