【问题标题】:Translate text into english under certain conditions, python在某些条件下将文本翻译成英文,python
【发布时间】:2022-10-18 05:07:11
【问题描述】:

我写了一个函数,它接受一个数据框和一个布尔列表。如果布尔列表中的值为 0,那么我们知道文本不是英文的位置。我编写了这个函数,但我不认为它是 Pythonic 并且遵循最佳实践。

def translate_text(df, mask):
    gs = goslate.Goslate()
    for sd, d, r, m in zip(df['short_description'], df['details'], df['resolution'], mask):
        if m == 0:
            # Perform translation
            sd = gs.translate(sd, 'en')
            d = gs.translate(d, 'en')
            r = gs.translate(r, 'en')
            
    return df

有没有更蟒蛇的方式来实现后者?任何建议表示赞赏。

这是一个示例

d = {'short_description': ['There is a problem with the laptop', 'Problemo y computer', 'There is a problem with the screen'],
    'details': ['The laptop will not respond, just a black screen', 'Problemo y computer', 'The screen is just blinking'],
    'resolution': ['Laptop has been replaced', 'La computadora ha sido reemplazada', 'Screen has been replaced']}
df_sample = pd.DataFrame(data=d)
mask = [1,0,1]

【问题讨论】:

  • 我已经更新了我的代码的某些部分,看看这对你是否可行?

标签: python pandas


【解决方案1】:

您可以将布尔值作为列放在数据框中,并使用loc 过滤掉需要翻译的行。此外,您可以定义一个接收数组并进行转换的函数。

# function to translate language
def translation(array):
    return [gs.translate(i, 'en') for i in array]

df_sample['boolean'] = mask

# Condition for loc
condition = (df_sample['boolean'] == 0, ['short_description','details','resolution'])

df_sample.loc[condition] = df_sample.loc[condition].apply(lambda x: translation(x.values))

【讨论】:

  • 我们可以一次应用此策略一列,即 short_description、details、resolution 假设我们每个都有唯一的掩码列表吗?
  • 我实际上收到此错误ValueError: Must provide strings.
猜你喜欢
  • 2021-10-05
  • 2019-01-09
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多