我得到了一个带有特殊字符(应该是法语字符)的字符串,并希望它在 csv/excel 中正确显示:
s1 = 'Benoît'
# take a look at encoding
print(s1.encode(encoding='utf-8'))
# print to txt
with open("firstname.txt", "w") as text_file:
print(s1, file=text_file)
# print to csv
import pandas as pd
df = pd.DataFrame({'FirstName': [s1]})
df.to_csv('firstname.csv', index = False)
结果 txt 文件正确显示法语,但 csv 不正确。
我的问题是如何让 csv 正确显示?(我可以将法语字符从 txt 复制到 csv,但是如何以编程方式编写 csv 并正确显示?)
更新:感谢@snakecharmerb,我试过了encoding = 'utf-8-sig'
# try csv with encoding = 'utf-8-sig': doesn't work
df = pd.DataFrame({'a': [s1]})
df.to_csv('firstname.csv', index = False, encoding = 'utf-8-sig')
# read from txt file which seems to display correctly
df = pd.read_table("firstname.txt", header = None)
df
# 0
# 0 Benoît
# then write to csv with encoding = 'utf-8-sig' - works
df.to_csv('firstname1.csv', index = False, encoding = 'utf-8-sig')