Skip to main content
 首页 » 编程设计

python之使用python将带有俄语字符的二维数组打印到csv

2025年05月04日9me-sa

我有一个二维数组,其中包含俄语/阿拉伯语/中文字符。我不确定如何将所有内容打印到 CSV 文件中。我想以 UTF-8 格式将其打印到 CSV 文件中。下面列出了我正在使用的代码。

matchedArray = [[]] 
matchedArray.append(x) 
 
ar = matchedArray 
 
f1 = open('C:/Users/sagars/Desktop/encoding.csv','w') 
writer = csv.writer(f1) 
writer.writerow(['Flat Content', 'Post Dates', 'AuthorIDs', 'ThreadIDs', 
                 'Matched Keyword', 'Count of keyword']) #if needed 
for values in ar: 
    writer.writerow(values) 

但是,我收到以下错误:

Traceback (most recent call last): 
  File "C:/Users/sagars/PycharmProjects/encoding/encoding.py", line 18, in <module> 
    writer.writerow(values) 
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-13: ordinal not in range(128) 
 
Process finished with exit code 1 

如何将此二维数组打印到 CSV 文件?

谢谢!

请您参考如下方法:

您可以使用 str.encode在存储到 csv 文件之前使用正确的编码对每个字符进行编码。

for values in ar: 
    # values is a list/string of unicode characters 
    writer.writerow([val.encode("utf-8") for val in values])