python - 使用按字长排序的字典翻译熊猫数据框
问题描述
我已将 excel 导入到 pandas 数据框,我正在尝试将其翻译然后导出回 excel。
例如目的说这是我的数据集:
d = {"cool":"chill", "guy":"dude","cool guy":"bro"}```
data = [['cool guy'], ['cool'], ['guy']]
df = pd.DataFrame(data, columns = ['WORDS'])
print(df)
# WORDS
# 0 cool guy
# 1 cool
# 2 guy
所以最简单的解决方案是使用 pandas 内置的函数替换。但是,如果您使用:
df['WORDS'] = df['WORDS'].replace(d, regex=True)
结果是:
print(df)
# WORDS
# 0 chill dude
# 1 chill
# 2 dude
(帅哥翻译不正确)
这可以通过首先按最长单词对字典进行排序来解决。我尝试使用此功能:
import re
def replace_words(col, dictionary):
# sort keys by length, in reverse order
for item in sorted(dictionary.keys(), key = len, reverse = True):
col = re.sub(item, dictionary[item], col)
return col
但..
df['WORDS'] = replace_words(df['WORDS'], d)
导致类型错误:
TypeError: expected string or bytes-like object
尝试将行转换为字符串也无济于事
...*
col = re.sub(item, dictionary[item], [str(row) for row in col])
有没有人可以尝试任何解决方案或不同的方法?
解决方案
让我们试试replace
df.WORDS.replace(d)
Out[307]:
0 bro
1 chill
2 dude
Name: WORDS, dtype: object
推荐阅读
- vim - 有没有办法在不使用匹配的情况下突出显示默认的 vim 关键字?
- php - Laravel 如何优化内存中昂贵的计算?
- express - 如何优雅地处理 express 中的 promise 拒绝
- html - 如果父容器旋转,如何不旋转文本
- loops - 如何在haskell中使用do和while循环
- python - 为什么使用 plt.imshow 显示后输出与变量的值不同?
- oracle - 如何将 MMMYYYY 字符串转换为 Oracle 中的日期?
- azure - 我需要在我的 Azure AD 中为用户设置“工作信息”,例如“部门”。Set-AzADUser 没有此参数。还有其他命令吗?
- node.js - Mongodb $lookup 与预初始化
- python - 如何从for循环中的类中获取实例名称