Python与PyCharm的中文显示问题

最近在编写Python爬虫,用的Python2.7中文在IDE里的显示非常蛋疼,

我用的IDE是PyCharm 2018.1...

爬取的数据经常无法显示出中文,(估计一大部分是print语句的锅..) 想特意总结一下:

1. 每个.py文件开头加

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


这样就可以在.py文件中出现中文了, 例如中文注释,注意这个声明和print内容以及文件输出没有任何关系

2. 爬下来的JSON 解析后一直print成类似'\xe8\xbc\xaa\xe3'的unicode码

试了很多方法都没用,特别奇怪的时候我发掘可能是解析的时候添加了转义字符.... 比如'\xe8'是按照'\\xe8'存的...
所以用string_escape试了一下, 果然可以顺利输出了..解决了一大问题

print(str(painterMap).decode('string_escape'))


3. PyCharm设定

为了让pycharm输出显示正确中文,File-> Settings -> File encoding -> utf-8
这里我的project encoding 设置为system default (GBK)貌似也可以的..

4. 中文乱码

遇到乱码的情况95%是编码问题.. 用decode()/encode()解决...要具体爬取下来数据的编码具体分析

    str1 = u'你好啊'  # unicode Chinese Chars
    str2 = str1.encode('gb2312')  # encode str1 with gbk coding
    str3 = str1.encode('utf-8')  # encode str1 with utf-8 coding
    str4 = str2.decode('gb2312')  # decode str1 with gbk coding
    print(str1)
    print(str2)
    print(str3)
    print(str4)


5.  中文路径

在输入中文路径获取文件的时候会告诉我文件不存在...

例如: D:\python\年终总结.docx

需要对路径进行unicode加密成: (r'xxx' 表示强制不转义)

path = unicode(r'D:\python\年终总结.docx', 'utf8')


或者直接用u'XXX':

file = open(u'D:\\python\\年终总结.docx', 'rb')


--------------------- 
作者:PerryXu_BIT 
来源:CSDN 
原文:https://blog.csdn.net/perry_x/article/details/80274714 

猜你喜欢

转载自blog.csdn.net/sinat_34166518/article/details/84399548
今日推荐