简体   繁体   English

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

[英]How can i correct my error and make the dataframe a text file using functions in python

I am creating a function to convert a dataframe to a .txt file.我正在创建一个将数据帧转换为 .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."]})

This is how i want the .txt file to look like这就是我希望 .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."

But this is the error i am getting但这是我得到的错误

UnicodeEncodeError: 'charmap' codec can't encode character '\ń' in position 14: character maps to UnicodeEncodeError: 'charmap' codec can't encode character '\ń' in position 14: character maps to

This largely works for me:这在很大程度上对我有用:

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()

I think the bit you're missing is the "encoding='utf-8'".我认为您缺少的一点是“encoding='utf-8'”。 Hope this helps!希望这可以帮助!

In this case, it would seem that there is an issue between your input text encoding and the panda output encoding on which you are trying to perform.在这种情况下,您的输入文本编码和您尝试执行的熊猫输出编码之间似乎存在问题。

Please take a look at this answer: here on how to handle encoding and decoding characters when writing and reading characters (you may need different to UTF-8!)请看一下这个答案:这里是关于如何在写入和读取字符时处理编码和解码字符(您可能需要与 UTF-8 不同!)

As for styling the output, an easier mechanism may to use csv as shown here and use spaces for delimiting seeing as your data is already in a tabular form from pandas.至于输出的样式,一种更简单的机制可能是使用 csv,如下所示并使用空格来分隔视图,因为您的数据已经是来自 Pandas 的表格形式。

This worked in my case as an alternative to using joins.在我的情况下,这可以作为使用连接的替代方法。 If you have any other problems, please try use encode/decode.如果您有任何其他问题,请尝试使用编码/解码。

import pandas as pd
import csv

def print_table(dataframe):  
    with open('file.csv', 'w', newline="") as csvfile:
        writer = csv.writer(csvfile, delimiter="\t", quotechar='', quoting=csv.QUOTE_NONE)
        writer.writerow(heading) for heading in dataframe.columns)

        for row in dataframe.values:
            writer.writerow(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."
    ]
})

print_table(df)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 python 中的 json 文件制作漂亮的 dataframe? - How can I make pretty dataframe using json file in python? Pandas/Python:如何使用函数过滤 Dataframe 或系列? - Pandas/Python: How can I filter a Dataframe or Series by using functions? 如何让 Python 识别 DataFrame 单元格中的星号? - How can I make Python recognize an asterisk in a cell of my DataFrame? 如何更正在 python 中有值错误的代码? - How can I correct my code that has a value error in python? 如何使用函数使我的代码更加优化? - How can I make my code more optimised using functions? 我如何在 python 中使用 for 循环制作 pandas dataframe 对象 - how can i make pandas dataframe objects using for loop in python 如何使用Sublime Text按字母顺序排列Python函数? - How can I alphabetize Python functions using Sublime Text? 如何在我的python程序中显示以下文本? - How can I make the following text appear in my python program? 如果我的脚本使用从其他文件导入的函数,如何让我的脚本从 Unix 上的可执行 python 文件运行? (ModuleNotFoundError) - How can I make my script run from executable python file on Unix if it uses functions imported from other files? (ModuleNotFoundError) 如何使用 Python 将我的 DataFrame 转换为雷达图? - How can I turn my DataFrame into a Radar Chart using Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM