pujvzi的个人博客分享 http://blog.sciencenet.cn/u/pujvzi

博文

Ubantu乌班图python2.7 处理的文本,以及脚本中的 中文 的解码

已有 2440 次阅读 2018-12-14 16:23 |个人分类:生信|系统分类:科研笔记| python, 中文, 编码, 乱码

Ubantu乌班图python2.7 处理的文本,以及脚本中的 中文 的解码



##########################################################################
在linux中(乌班图)中,python2.7在处理中文文本,并且脚本中含有中文时

1, 在脚本的首行加
# -*- coding: UTF-8 -*-

2, python在读入中文时,将文字读成 gbk 格式。但出现在脚本里的汉字,是别的格式(UTF-8 ??)。

3, 比对   脚本中的中文   与    从文件中读取的中文   时,需要将两者转换成相同的编码格式。

比如:

变量  X  是从文本里独到的文字    “彪”
脚本里如果写成
if X == '彪':
是不成的。正确的方法是:
if X.strip() == '彪'.decode('utf-8').encode('gbk'):

strip()是为了去除\r\t\n等汉字之外的东西。
'彪'.decode('utf-8').encode('gbk'),是将 脚本里出现的 ‘彪’ 字,改成了 gbk 编码。

###########################################################################





#########################################################

此外,如果linux终端显示中文为乱码,在终端的视窗的菜单里,找encoding,改成中文简体。

#########################################################









>>> a = '好'
>>> type(a)
<type 'str'>
>>> b = a.decode('utf-8')
>>> type(b)
<type 'unicode'>
>>> c = a.decode('utf-8').encode('utf-8')
>>> type(c)
<type 'str'>
>>> print(a)

>>> print(b)

>>> print(c)

>>> a
'\xe5\xa5\xbd'
>>> b
u'\u597d'
>>> c
'\xe5\xa5\xbd'
>>> d = a.decode('utf-8').encode('GB2312')
>>> type(d)
<type 'str'>
>>> d
'\xba\xc3'
>>> print(d)
��
>>> e = b.decode('utf-8').encode('GB2312')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u597d' in position 0: ordinal not in range(128)
>>>









https://blog.sciencenet.cn/blog-331314-1151541.html

上一篇:卵母细胞凋亡信号检测(JC-1标记法)
下一篇:睾丸生殖细胞的免疫荧光标记
收藏 IP: 61.140.242.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-24 16:43

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部