【问题标题】:translate dataframe python to english and save the result into a cvs file将数据框 python 翻译成英文并将结果保存到 cvs 文件中
【发布时间】:2021-04-21 22:48:55
【问题描述】:

我有一个包含 205232 行的数据框,我想将单行中可以包含一种或多种语言的列“ingredients_text”翻译成英文。这是df的一个例子

我尝试了两种翻译方法,但没有成功: 代码1:

import googletrans    
from googletrans import Translator
translator = Translator()
df['transalted']= df['ingredients_text'].apply(translator.translate ,dest='en').apply(getattr, args=('text',))
#then i want to save the result into a csv file

代码 2:

import googletrans
from googletrans import Translator
translator = Translator()
for column in df['ingredients_text']: 
   translation=translator.translate(column, dest='fr').text
#then i want to save the result into a csv file

非常感谢您的帮助。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用 lambda 函数尝试 apply()。然后使用pandas.DataFrame.to_csv()将dataframe转成csv。

    import googletrans    
    from googletrans import Translator
    
    
    translator = Translator()
    df['transalted'] = df['ingredients_text'].apply(lambda x: translator.translate(x, dest='en').text)
    
    df.to_csv('your.csv')
    
    # If you only want translated result,
    # you can use
    df['transalted'].to_csv('your.csv')
    

    【讨论】:

    • 翻译效果很好,但保存在 csv 中会出错:OSError: [Errno 95] Operation not supported: 'translated.csv'
    • @Yoss df.to_csv('your.csv') 和 df['transalted'].to_csv('your.csv') 你用的是哪一个?您只需选择其中之一即可。
    • 我需要保存所有的 df => df.to_csv('your.csv') ,我正在使用 google colab
    • @Yoss 我不使用 google colab。检查Export dataframe as csv file from google colab to google drive 是否有熊猫导出。
    猜你喜欢
    • 2021-10-05
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 2019-01-09
    • 2018-09-11
    • 2013-12-18
    • 1970-01-01
    相关资源
    最近更新 更多