【问题标题】:Translate pandas column with TextBlob使用 TextBlob 翻译 pandas 列
【发布时间】:2015-11-13 11:21:24
【问题描述】:

我正在尝试读取 csv 并使用 Python (2.7.10 Mac OS X Yosemite) 中的 TextBlob 包将用法语编写的一列翻译成英语。

但是,Python 向我抛出以下错误消息:

AttributeError: 'Series' object has no attribute 'translate'

我的 Python 代码:

import pandas as pd
import numpy as np
from textblob import TextBlob

df = pd.read_csv('france_content.csv')
df2 = df[['HEADLINE', 'AUTHOR', 'CONTENT']]

TextBlob = df2['CONTENT'].str.strip()
TextBlob.translate(to="es")

再想一想,我实际上认为我在这里不需要 numpy。但是我怎样才能让熊猫阅读内容字段并让 textblob 将其翻译成英文。最好将其放在名为“英语”的列中

编辑: 改为:

import pandas as pd
import numpy as np
from textblob import TextBlob

df = pd.read_csv('france_content.csv')

df['English'] = df['CONTENT'].str.encode('ascii', 'ignore').apply(lambda x:    TextBlob(x.strip()).translate(to='en'))

数据非常基本,第 1 列作者姓名和第 2 列(“内容”)法文文本。

我仍然有以下错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 9: ordinal not in range(128)

【问题讨论】:

  • IIUC df['English'] = df['CONTENT'].apply(lambda x: TextBlob.translate(x.strip(), to='es')) 工作吗?
  • 不,那没用。 TypeError: unbound 方法 translate() 必须使用 TextBlob 实例作为第一个参数调用(而不是 str 实例)
  • 嗯,试试这个df['English'] = df['CONTENT'].apply(lambda x: TextBlob(x.str.strip()).translate(to='es'))
  • 在 IDLE 中运行但出现以下错误:AttributeError: 'str' object has no attribute 'str'
  • 试试df['English'] = df['CONTENT'].apply(lambda x: TextBlob(x.strip()).translate(to='es'))

标签: python pandas textblob


【解决方案1】:
import pandas as pd
from textblob import TextBlob
df = pd.read_csv('d:\lan.csv') # path to csv file

在数据框中添加带有转换后单词的英文列

df['english'] = df['structure'].str.encode('ascii', 'ignore').apply(lambda x:TextBlob(x.strip()).translate(to='en'))
df.to_csv("cool.csv")# your documents folder

这按要求工作。

谢谢

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 2016-05-27
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多