如何使用 Anaconda 使用 python3 将 'utf-8' 写入新的 CSV 文件?

How to write 'utf-8' to a new CSV file using python3 with Anaconda?

如何使用 python3 和 Anaconda 将 'utf-8' 写入新的 CSV 文件?

我是 python 和 pandas 的新手。我使用的版本是python3。我运行它用Anaconda平台,一个IDE和PyCharmIDE一样IDE。

我有两个数组来记录长文本中的所有单词及其出现频率。所有单词都以字符串形式保存,其中包括 'utf-8' 个字符:

value = [13, 4, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 

key = ['-', 'Span', 'Found', 'Not', '404.0', '详细', '8.5', 'IIS', 'Details', '错误', 'Machine,', 'K', 'Ltd.', 'Co.,', 'Contact', 'Group', 'Large', 'qinwomachine', 'Trading', 'Qinwo', 'Shanghai', 'Manufacturer', 'Machine', 'Super', 'Abm240', 'Abm120', 'Mic240', 'Mic120', 'Forming', 'Roll', 'wubianstar', 'Electrical', 'Hont', 'China', 'tileformer', '\ufeffContact']

现在我正在尝试使用 python3 和 Anaconda 将这些值和键数组写入一个名为 split_word.csv 的新 CSV 文件。我的代码如下:

# read the arrays as dataframe, also set the column name 'word' and 'frequency'
df = pd.DataFrame({"word" : newkey, "frequency" : newvalue}) 

# write dataframe into a new csv file
df.to_csv("split_word.csv", index=False)

我在 csv 中的预期结果是两个新列:

frequency   word
13          -
4           Span
3           Found
3           Not
3           404
3           详细
3           8.5
3           IIS
3           Details
2           错误
2           Machine,
2           K
2           Ltd.
2           Co.,
2           Contact

但是实际结果有问题。缺少“详细”和“错误”:

frequency   word
13          -
4           Span
3           Found
3           Not
3           404
3           ????
3           8.5
3           IIS
3           Details
2           ????
2           Machine,
2           K
2           Ltd.
2           Co.,
2           Contact

所以唯一的问题是 'utf-8' 输入。我应该在代码中添加解码还是编码?如何解决这个简单但烦人的问题?

非常感谢!

您只需指定编码:

df.to_csv("split_word.csv", index=False, encoding="utf-8")