[英]Python: translating a Excel sheet from Chinese to English
I am new to Python and I am trying to translate a Excel Sheet from Chinese to English.我是 Python 的新手,我正在尝试将 Excel 工作表从中文翻译成英文。 Id love to have a drag and drop field to load the Data Source but I am trying to get it to work first.我喜欢有一个拖放字段来加载数据源,但我想先让它工作。
import sys
import pandas as pd
from googletrans import Translator
# read from an excel file
df = pd.read_excel('TestBericht.xlsx')
# translate a column to English, and add back into the DataFrame
translator = Translator()
df['transKunde'] = df['F9'].apply(translator.translate,src='zh-CN',dest='en').apply(getattr, args=('text',))
# output new excel file
df.to_excel('translatedFile.xlsx')
Now if I run the code it throws me a KeyError:现在,如果我运行代码,它会抛出一个 KeyError:
AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\indexes\base.py", line 3802, in get_loc
return self._engine.get_loc(casted_key)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 5745, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 5753, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'F9'
Desktop\Uebersetzer.py", line 10, in <module>
df['transKunde'] = df['F9'].apply(translator.translate,src='zh',dest='en').apply(getattr, args=('text',))
~~^^^^^^
KeyError: 'F9'
I have been going through stackoverflow to find a solution but I didnt find anything.我一直在通过 stackoverflow 寻找解决方案,但我没有找到任何东西。 The Script I am referring to is from: Excel sheet translation using python我指的脚本来自: Excel sheet translation using python
You can use df.iat[row, column]
to access exactly the cells you need:您可以使用df.iat[row, column]
来准确访问您需要的单元格:
Access a single value for a row/column pair by integer position.通过 integer position 访问行/列对的单个值。
Similar to
iloc
, in that both provide integer-based lookups.与iloc
类似,两者都提供基于整数的查找。 Use iat if you only need to get or set a single value in a DataFrame or Series.如果您只需要获取或设置 DataFrame 或系列中的单个值,请使用 iat。
Remember that pandas take the first column and first row as the header/fields of the data.请记住,pandas 将第一列和第一行作为数据的标题/字段。 Pandas also uses 0 as the starting index, so your coordinate would be 9-2,F-2
-> [7,4]
like so: Pandas 也使用 0 作为起始索引,因此您的坐标将是9-2,F-2
-> [7,4]
,如下所示:
df['transKunde'] = df.iat[7,4].apply(translator.translate,src='zh-CN',dest='en').apply(getattr, args=('text',))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.