如何使用Python编程实现批量Excel文件中的英文内容翻译成中文?完整代码
时间: 2024-12-19 13:20:57 浏览: 19
要使用Python编程实现批量Excel文件中的英文内容翻译成中文,可以借助`openpyxl`库读取Excel文件,`googletrans`库进行翻译,并使用`pandas`处理数据。这里是一个简化的示例:
首先,确保已安装所需库:
```bash
pip install openpyxl pandas googletrans==4.0.0-rc1
```
然后编写一个简单的脚本:
```python
import os
from openpyxl import load_workbook
from googletrans import Translator
import pandas as pd
# 创建Translator实例
translator = Translator()
def translate_cell(cell):
try:
# 如果单元格内容是英文
if cell.value and isinstance(cell.value, str) and cell.value.lower().isalpha():
translation = translator.translate(cell.value, src='en', dest='zh-cn')
return translation.text
else:
return cell.value
except Exception as e:
print(f"Error translating cell {cell}: {e}")
return cell.value
def batch_translate_excel(input_folder, output_folder):
for filename in os.listdir(input_folder):
if filename.endswith(".xlsx"):
full_path = os.path.join(input_folder, filename)
# 加载工作簿
wb = load_workbook(full_path)
ws = wb.active
# 使用pandas将工作表转换为DataFrame
df = pd.DataFrame(ws.values, columns=ws row_dimensions.keys())
# 将所有英文文本列应用翻译函数
df_translated = df.applymap(translate_cell)
# 保存翻译后的结果到新的Excel文件
new_filename = f"{os.path.splitext(filename)[0]}_translated.xlsx"
new_full_path = os.path.join(output_folder, new_filename)
df_translated.to_excel(new_full_path, index=False)
# 设置输入和输出目录
input_folder = "path_to_your_input_folder"
output_folder = "path_to_your_output_folder"
batch_translate_excel(input_folder, output_folder)
```
**
阅读全文