python - Pandas Excel 行提取更改字段
问题描述
我在一个小型翻译程序上工作。我有一个 .xlsx 文件,每个文件有 5 列,每列使用不同的语言(英语、法语、德语、西班牙语、意大利语)。
该程序提供了一个下拉列表,其中 .xlsx 中的每一行都是可用选项之一(仅限英语)。选择其中一个选项将获取英语值并将其添加到列表中。
然后,我使用以下内容稍后根据 deliminator(;) 选择和拆分的英语提取整行其他语言:
instructionList = ['Avoid contact with light-coloured fabrics, leather and upholstery. Colour may transfer due to the nature of indigo-dyed denim.']
for i in range(len(instructionList)):
newCompInst.append(translationFile.loc[translationFile['English'] == instructionList[i]].to_string(index=False, header=False))
newInst = [i.replace(' ', ',;') for i in newInst ]
strippedInst = [item.lstrip() for item in newInst ]
print('strippedInst: ', strippedInst)
我从以下代码得到的输出是:
strippedInst: ['Avoid contact with light-coloured fabrics, lea...,;Bviter le contact avec les tissus clairs, le c...,;Kontakt mit hellen Stoffen, Leder und Polsterm...,;Evitar el contacto con tejidos de colores clar...,;Evitare il contatto con capi dai colori delica...']
运行此代码后,所有语言都被切成两半,句子的其余部分被替换为 '...' - (注意 'strippedInst' 中的英语并与输入到循环中的内容(指令列表)进行比较。
只有当句子很长时,输出才会被削减。我尝试运行较小的短语,这一切似乎都很好。
这是预期的输出:
strippedInst:
['
Avoid contact with light-coloured fabrics, leather and upholstery. Colour may transfer due to the nature of indigo-dyed denim.,;
Éviter le contact avec les tissus clairs, le cuir et les tissus d'ameublement. Les couleurs peuvent déteindre en raison de la nature de la teinture indigo du denim.,;
Kontakt mit hellen Stoffen, Leder und Polstermöbeln vermeiden. Aufgrund der Indigofärbung kann sich die Farbe übertragen,;
Evitar el contacto con tejidos de colores claros, con cuero y con tapicerías. El tinte índigo de los vaqueros podría transferirse a dichas superficies.,;
Evitare il contatto con capi dai colori delicati, pelli e tappezzerie. Si potrebbe verificare una perdita del colore blu intenso del tessuto di jeans.,
']
编辑:这是整个独立的工作功能:
import pandas as pd
excel_file = 'C:/Users/user/Desktop/Translation_Table_Edit.xlsx'
translationFile = pd.read_excel(excel_file, encoding='utf-8')
compList = ['Avoid contact with light-coloured fabrics, leather and upholstery. Colour may transfer due to the nature of indigo-dyed denim.', 'Do not soak']
newComp = []
def myFunction():
global newComp
for i in range(len(compList)):
newComp.append(translationFile.loc[translationFile['English'] == compList[i]].to_string(index=False, header=False))
newComp = [i.replace(' ', ';') for i in newComp]
myFunction()
strippedComp = [item.lstrip() for item in newComp]
print(strippedComp)
这将输出以下内容:
['Avoid contact with light-coloured fabrics, lea...;�viter le contact avec les tissus clairs, le c...;Kontakt mit hellen Stoffen, Leder und Polsterm...;Vermijd contact met lichtgekleurde stoffen, le...;Evitar el contacto con tejidos de colores clar...;Evitare il contatto con capi dai colori delica...', 'Do not soak;Ne pas laisser tremper;Nicht einweichen;Niet weken;No dejar en remojo;Non lasciare in ammollo']
解决方案
问题在于调用to_string
数据框。相反,首先将值提取到一个数组中 ( df_sub.iloc[0].values
),然后连接该列表的元素 ( ';'.join(...)
)。
这应该可以解决问题:
def myFunction():
global newComp
for i in range(len(compList)):
df_sub = translationFile.loc[translationFile['English'] == compList[i]]
if df_sub.shape[0] > 0:
newComp.append(';'.join(df_sub.iloc[0].values))
编辑:建议的代码改进
此外,(在我看来)您的代码可以通过以下方式改进(使用 pandas 功能而不是循环,遵守 pep8 中的命名约定,避免使用全局变量):
import pandas as pd
df_translations = pd.read_excel('./Translation_Table_Edit.xlsx', encoding='utf-8')
to_translate = ['Avoid contact with light-coloured fabrics, leather and upholstery. Colour may transfer due to the nature of indigo-dyed denim.',
'Do not soak']
def get_translations(df_translations, to_translate, language='English'):
"""Looks up translatios for all items in to_translate.
Returns a list with semi-colon separated translations. None if no translations found."""
df_sub = df_translations[df_translations[language].isin(to_translate)].copy() # filter translations
df_sub = df_sub.apply(lambda x: x.str.strip()) # strip each cell
# format and combine translations into a list
ret = []
for translation in df_sub.values:
ret.append(';'.join(translation))
return ret
translations = get_translations(df_translations, to_translate)
推荐阅读
- html - wxPython 创建饼图的其他方式
- android - Android Studio - 无效与重新启动与无效和重新启动
- javascript - 如何在 Angular 项目中使用 ng-circle-progress src 代码?
- python-3.x - 导入熊猫时出错。ImportError: 无法导入名称 'Timestamp' 。
- python - 如何让 Python 中的线程等待?
- android-studio - Flutter:调试集成测试
- r - 使用 R 中的插入符号包绘制具有交叉验证的多类分类的学习曲线
- groovy - 如何使用 Ant Build 脚本打包 Groovy 类或 Groovy 项目?
- javascript - 在我的 fish / cygwin shell 上使用 Node.js
- c++ - 在 c++ 中给出意外输出的简单代码