Python 3 中文文档编码问题

在做中文文本情感分类预处理时,编码问题着实浪费我不少时间,总结如下:

1.  文件是中文,内容是酒店评论,首先是打开文件和写入新文件。

因为pickle存储默认为是二进制形式,在Python中为bytes类型,打开和写入方式需用二进制方式:

# 读取文件内容
def getContent(filename):
    with open(filename, 'rb') as f:    # 打开该中文文件的方式需二进制方式打开:rb
        contents = f.readline()
        f.close()
        return contents
result_file = open(result_path, 'wb+')   # 同样新建的储存中文的文件也要是二进制方式:wb+
result_file.write(content)

2. 对整合好的文件进行分词再存储时,同样要保证编码格式

def prepareData(sourcefile, targerfile):
    source = codecs.open(sourcefile, 'rb')
    target = codecs.open(targerfile, 'w', encoding='utf-8')
    for line in source:
        line = line.decode('gbk', 'ignore')
        line = clearTxt(line)
        seg_line = sent2word(line)
        target.writelines(seg_line + '\n')
读入时需将二进制格式decode为str类型,且因为decode的函数原型是decode([encoding], [errors='strict']),可以用第二个参数控制错误处理的策略,默认的参数就是strict,代表遇到非法字符时抛出异常; 
如果设置为ignore,则会忽略非法字符; 
如果设置为replace,则会用?取代非法字符; 

如果设置为xmlcharrefreplace,则使用XML的字符引用。

新建文件并写入时,可在新建时进行编码格式标记,这样writelines()时就可以直接写入了。


猜你喜欢

转载自blog.csdn.net/sinat_36972314/article/details/79585508