用Python脚本解决Linux上MapReduce输出结果中的中文乱码问题

问题介绍

Windows上跑出的结果中的中文显示没有问题,但是在Linux上由于编译环境问题却是中文乱码。

解决方案

利用Python脚本,快速完成编码转换。但是查找资料的过程比较艰辛,尝试了很多种办法都没能成功,最终用pydoop包对HDF上的MapReduce结果进行操作,解决问题。

import pydoop.hdfs as hdfs
import chardet

for info in hdfs.lsl("your path"):
        if info['path'][-1] == 'S': #_SUCCESS文件排除
                continue
        try:
                with hdfs.open(info['path'][12:],'r') as fi:
                        content = fi.read()
                        se = chardet.detect(content)['encoding']
                        print se
                        #用'GB18030'格式,经查找资料,包含字符个数GB2312 < GBK < GB18030,避免了前两种会报错的问题
                        content = content.decode("GB18030").encode("UTF-8")
                        hdfs.dump(content, info['path'][12:])
        except IOError as err:
                print("I/O error:{0}".format(err))

猜你喜欢

转载自blog.csdn.net/tonybao912/article/details/80583430
今日推荐