加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Python为什么偏爱ANSI格式编码?

(2014-06-24 14:01:03)
分类: Python

http://s12/mw690/001mb2IGgy6JVmG389leb&690



我昨天遇到一个疑惑,使用python读入中文,然后print读入的文本,却显示为乱码。


os.chdir("C:/Users/v_chjwang/Desktop/weibosent/SentiAnalysis_local")

file = open("./test2.txt", 'r')


def read_file(file_name):

txt = []

for i in file_name:

line = i.split(',')[0]

txt.append(line)

return txt

txt = read_file(file)


>>> txt[1]

'\xe8\xbf\x99\xe9\x83\xa8\xe6\x89\x8b\xe6\x9c\xba\xe5\xbe\x88\xe4\xb8\x8d\xe9\x94\x99\xe3\x80\x82\n'

>>> print txt[1]   

杩欓儴鎵嬫満寰堜笉閿欍€   


我想一定是我的encoding没有设置好,python是偏爱unicode的,我还是先声明一些基础的东西吧。尝试指定软件型号、编码方式、使用sys设置预定的encoding,如下:



#! /usr/bin/env python2.7

# -*- coding:utf-8-*-

#coding=utf-8

import os

import sys


reload(sys)

sys.setdefaultencoding('utf-8')


结果还是不行。错误依旧。


到底是怎么回事呢?我尝试着将文本的encoding由utf-8改成ANSI,结果就正确了。如下效果:


>>> txt[1]

'\xd5\xe2\xb2\xbf\xca\xd6\xbb\xfa\xba\xdc\xb2\xbb\xb4\xed\xa1\xa3\n'

>>> print txt[1]   

这部手机很不错。


这是为什么呢?这个博客提供了一个例子:http://hi.baidu.com/derris/item/56c5048e2c6d6bd45f0ec1d8


程序:===================
a = '中文'
b = u'中文'
print a, type(a)
print b, type(b)
print a.decode('gbk')
--------------------------------------
文件格式ansi
#coding=gbk
输出:
中文
中文
中文 ( print a.decode('gbk') )
--------------------------------------
文件格式utf8带bom
输出:
涓 枃
中文
中文 ( print a.decode('utf8') )
--------------------------------------

他的结论也是说:所以感觉还是用#coding=gbk的ansi格式的存储比较好。




0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有