python 字符编码有关问题

python 字符编码问题

preface: 承接上一条博客,帮师兄处理json文件读入数据库中。python读入数据到数据库中,出现编码问题。python里面定义了utf-8,然而文件中有日文、韩文、其他符号、拉丁编码等等,对编码不够熟悉果然是要死银的,弄了挺久的,却终究一个函数可破。encode()函数。

decode()和encode()这两个函数,有空的时候还是多看看才是。

# -*- coding: utf-8 -*-
"""
Created on Fri Jul 10 16:49:56 2015

@author: shifeng
"""
import codecs
import json
import sys
reload(sys)    
sys.setdefaultencoding('utf8') 

f = codecs.open("xxx.json")
for line in f:
    line_dict = json.loads(line)
    text = line_dict["text"]
    text = text.encode(encoding="utf-8",errors = "ignores")
xxx.json文件中,text字段的值包含中文、拉丁编码、日文、韩文等。


版权声明:本文为博主原创文章,未经博主允许不得转载。