Python CSV写入文件在Excel中无法读取(中文字符)

时间:2015-12-27 15:06:54

标签: python excel csv unicode

我正在尝试对中文文本进行文本分析。该计划如下。我得到的结果是浜烘皯鏃ユ姤绀捐等不可读的字符。如果我将输出文件result.csv更改为result.txt,则字符正确为人民日报社论。那有什么不对呢?我弄不清楚。我尝试了多种方法,包括添加decoderencoder

    # -*- coding: utf-8 -*-
    import os
    import glob
    import jieba
    import jieba.analyse
    import csv
    import codecs  

    segList = []
    raw_data_path = 'monthly_raw_data/'
    file_name = ["201010", "201011", "201012", "201101", "201103", "201105", "201107", "201109", "201110", "201111", "201112", "201201", "201202", "201203", "201205", "201206", "201208", "201210", "201211"]

    jieba.load_userdict("customized_dict.txt")

    for name in file_name:
        all_text = ""
        multi_line_text = ""
        with open(raw_data_path + name + ".txt", "r") as file:
            for line in file:
                if line != '\n':
                    multi_line_text += line
            templist = multi_line_text.split('\n')
            for text in templist:
                all_text += text
            seg_list = jieba.cut(all_text,cut_all=False)
            temp_text = []
            for item in seg_list:
                temp_text.append(item.encode('utf-8'))

            stop_list = []
            with open("stopwords.txt", "r") as stoplistfile:
                for item in stoplistfile:
                    stop_list.append(item.rstrip('\r\n'))

            text_without_stopwords = []
            for word in temp_text:
                if word not in stop_list:
                    text_without_stopwords.append(word)

            segList.append(text_without_stopwords)


    with open("results/result.csv", 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(segList)

2 个答案:

答案 0 :(得分:6)

对于UTF-8编码,Excel要求在文件开头写入BOM(字节顺序标记)代码点,否则它将采用ANSI编码,这与区域设置有关。 U+FEFF是Unicode BOM。这是一个将在Excel中正确打开的示例:

#!python2
#coding:utf8
import csv

data = [[u'American',u'美国人'],
        [u'Chinese',u'中国人']]

with open('results.csv','wb') as f:
    f.write(u'\ufeff'.encode('utf8'))
    w = csv.writer(f)
    for row in data:
        w.writerow([item.encode('utf8') for item in row])

为了完整起见,Python 3使这更容易。注意newline=''参数而不是wbutf-8-sig编码会自动添加BOM。 Unicode字符串是直接编写的,而不是需要对每个项目进行编码。

#!python3
#coding:utf8
import csv

data = [[u'American',u'美国人'],
        [u'Chinese',u'中国人']]

with open('results.csv','w',newline='',encoding='utf-8-sig') as f:
    w = csv.writer(f)
    w.writerows(data)

还有第三方模块unicodecsv也使Python 2更容易:

#!python2
#coding:utf8
import unicodecsv

data = [[u'American',u'美国人'],
        [u'Chinese',u'中国人']]

with open('results.csv','wb') as f:
    w = unicodecsv.writer(f,encoding='utf-8-sig')
    w.writerows(data)

答案 1 :(得分:0)

这是另一种有点棘手的方式:

#!python2
#coding:utf8
import csv

data = [[u'American',u'美国人'],
        [u'Chinese',u'中国人']]

with open('results.csv','wb') as f:
    f.write(u'\ufeff'.encode('utf8'))
    w = csv.writer(f)
    for row in data:
        w.writerow([item.encode('utf8') for item in row])

此代码块生成编码为utf-8的csv文件。

  1. 使用notepad ++(或其他带编码功能的编辑器)打开文件
  2. 编码 - > 转换为ANSI
  3. 保存
  4. 用Excel打开文件,没关系。