关于编码方式的问题
来源:7-7 数据预处理之分词

慕九州9175731
2018-11-23
老师您好,我的编码方式好像有问题,只有通过这种编码方式才能成功,而且按照您写的那个generate_seg_file函数很容易出现把新旧两个文件的内容全部抹掉。请问是什么原因呢?
写回答
1回答
-
正十七
2018-11-25
参考原始代码:
def generate_seg_file(input_file, output_seg_file): """Segment the sentences in each line in input_file""" with open(input_file, 'r') as f: lines = f.readlines() with open(output_seg_file, 'w') as f: for line in lines: label, content = line.decode('utf-8').strip('\r\n').split('\t') word_iter = jieba.cut(content) word_content = '' for word in word_iter: word = word.strip(' ') if word != '': word_content += word + ' ' out_line = '%s\t%s\n' % (label, word_content.strip(' ')) f.write(out_line.encode('utf-8'))
输出文件的编码一般应该是utf-8的,你的代码没有调encode函数,所以需要你打开文件的时候指定编码方式。
把旧文件内容抹掉的原因是因为代码中打开的就是一个文件啊,自然要覆盖。如果你不想让它覆盖,你可以指定其他的文件名。
022019-06-09
相似问题