我正在创建一个将数据帧转换为.txt文件的函数。
import pandas as pd
def print_table(dataframe):
headers = dataframe.columns.to_list()
table = dataframe.values.tolist()
with open('file.txt','w') as file:
file.write(''.join(column.rjust(40) for column in headers))
for row in table:
with open('file.txt','w') as file1:
file1.write(''.join(str(column).ljust(20) for column in row))
df = pd.DataFrame({'Yoruba': ['Wèrè èèyàn ní ńwípé irú òun ò sí; irú ẹ̀ẹ́ pọ̀ ó ju ẹgbàágbèje lọ.','Wọ́n ńpe gbẹ́nàgbẹ́nà ẹyẹ àkókó ńyọjú.'],
'Translation': ['Only an imbecile asserts that there is none like him or her; his or her likes are numerous, numbering more than millions.',
'The call goes out for a carpenter and the woodpecker presents itself.'],
'Meaning': ['No one is incomparable.',
"One should not think too much of one's capabilities."]})
这就是我想要的.txt文件的外观
Yoruba Translation Meaning
"Wèrè èèyàn ní ńwípé irú òun ò sí; irú ẹ̀ẹ́ pọ̀ ó ju ẹgbàágbèje lọ." "Only an imbecile asserts that there is none like him or her; his or her likes are numerous, numbering more than millions." "No one is incomparable."
"Wọ́n ńpe gbẹ́nàgbẹ́nà ẹyẹ àkókó ńyọjú." "The call goes out for a carpenter and the woodpecker presents itself." "One should not think too much of one's capabilities."
**and not this**
Yoruba Translation Meaning
"Wèrè èèyàn ní ńwípé irú òun ò sí; irú ẹ̀ẹ́ pọ̀ ó ju ẹgbàágbèje lọ." "Only an imbecile asserts that there is none like him or her; his or her likes are numerous, numbering more than millions." "No one is incomparable."
"Wọ́n ńpe gbẹ́nàgbẹ́nà ẹyẹ àkókó ńyọjú." "The call goes out for a carpenter and the woodpecker presents itself." "One should not think too much of one's capabilities."
但这是我得到的错误
UnicodeEncodeError:'charmap'编解码器无法在位置14编码字符'\ u0144':字符映射到
这在很大程度上对我有用:
fout = open("file.txt", 'w', encoding='utf-8')
df = df[['Yoruba', 'Translation', 'Meaning']]
lengths = [len(max(val, key=len)) for val in df.values.T]
for i in range(len(df.columns)-1):
fout.write("{heading:<{length}} ".format(heading=df.columns[i], length=lengths[i]))
fout.write("{}\n".format(df.columns[-1]))
rows, columns = df.values.shape
for i in range(rows):
for j in range(columns-1):
fout.write("{val:<{number}} ".format(val=df.values[i,j], number=lengths[j]))
fout.write("{}\n".format(df.values[i, j+1]))
fout.close()
我认为您缺少的是“ encoding ='utf-8'”。希望这会有所帮助!