Python CSV写入文件在Excel中不可读(中文字符)

disho6za  于 2023-01-31  发布在  Python
关注(0)|答案(2)|浏览(147)

我正在尝试对中文文本进行文本分析。下面提供了程序。我得到的结果是一些不可读的字符,例如浜烘皯鏃ユ姤绀捐。如果我将输出文件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)
xn1cxnb4

xn1cxnb41#

对于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使这变得更容易,使用'w', newline='', encoding='utf-8-sig'参数代替'wb''wb'将直接接受Unicode字符串并自动写入BOM:

#!python3
#coding:utf8
import csv

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

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)
cnwbcb6i

cnwbcb6i2#

这是另一个有点棘手的方法:

#!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.用记事本++打开文件(或其他具有编码功能的编辑器)
1.编码-〉转换为ANSI
1.保存
用Excel打开文件,就可以了。

相关问题