猿问

如何纠正我的错误并使用 python 中的函数使数据框成为文本文件

我正在创建一个将数据框转换为 .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."


但这是我得到的错误


UnicodeEncodeError:“charmap”编解码器无法在位置 14 编码字符“\u0144”:字符映射到


翻翻过去那场雪
浏览 136回答 2
2回答

婷婷同学_

这在很大程度上对我有用: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):&nbsp; &nbsp; fout.write("{heading:<{length}} ".format(heading=df.columns[i], length=lengths[i]))fout.write("{}\n".format(df.columns[-1]))rows, columns = df.values.shapefor i in range(rows):&nbsp; &nbsp; for j in range(columns-1):&nbsp; &nbsp; &nbsp; &nbsp; fout.write("{val:<{number}} ".format(val=df.values[i,j], number=lengths[j]))&nbsp; &nbsp; fout.write("{}\n".format(df.values[i, j+1]))fout.close()我认为您缺少的是“encoding='utf-8'”。希望这可以帮助!

慕勒3428872

在这种情况下,您的输入文本编码和您尝试执行的 panda 输出编码之间似乎存在问题。请看一下这个答案:here on how to handle encoding anddecode characters when writing and reading characters(你可能需要不同于UTF-8!)至于输出样式,一种更简单的机制可能是使用 csv,如此处所示, 并使用空格来分隔查看,因为您的数据已经是 pandas 的表格形式。在我的情况下,这可以作为使用连接的替代方法。如果您有任何其他问题,请尝试使用编码/解码。import pandas as pdimport csvdef print_table(dataframe):&nbsp;&nbsp;&nbsp; &nbsp; with open('file.csv', 'w', newline="") as csvfile:&nbsp; &nbsp; &nbsp; &nbsp; writer = csv.writer(csvfile, delimiter="\t", quotechar='', quoting=csv.QUOTE_NONE)&nbsp; &nbsp; &nbsp; &nbsp; writer.writerow(heading) for heading in dataframe.columns)&nbsp; &nbsp; &nbsp; &nbsp; for row in dataframe.values:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer.writerow(row)df = pd.DataFrame({&nbsp; &nbsp; 'Yoruba': [&nbsp; &nbsp; &nbsp; &nbsp; 'Wèrè èèyàn ní ńwípé irú òun ò sí; irú ẹ̀ẹ́ pọ̀ ó ju ẹgbàágbèje lọ.',&nbsp; &nbsp; &nbsp; &nbsp; 'Wọ́n ńpe gbẹ́nàgbẹ́nà ẹyẹ àkókó ńyọjú.'&nbsp; &nbsp; ],&nbsp; &nbsp; 'Translation': [&nbsp; &nbsp; &nbsp; &nbsp; 'Only an imbecile asserts that there is none like him or her; his or her likes are numerous, '&nbsp; &nbsp; &nbsp; &nbsp; 'numbering more than millions.',&nbsp; &nbsp; &nbsp; &nbsp; 'The call goes out for a carpenter and the woodpecker presents itself.'&nbsp; &nbsp; ],&nbsp; &nbsp; 'Meaning': [&nbsp; &nbsp; &nbsp; &nbsp; 'No one is incomparable.',&nbsp; &nbsp; &nbsp; &nbsp; "One should not think too much of one's capabilities."&nbsp; &nbsp; ]})print_table(df)
随时随地看视频慕课网APP

相关分类

Python
我要回答