import pandas as pd import langid from googletrans import Translator # 读取1.xlsx中的数据 df = pd.read_excel('1.xlsx') # 创建语言识别器 lang_detector = langid.langid.LanguageIdentifier.from_modelstring(langid.langid.model, norm_probs=True) # 创建翻译器 translator = Translator() # 遍历title和abs列的每个单元格 for i in range(len(df)): # 识别title列的语言 title_lang = lang_detector.classify(str(df.loc[i, 'title']))[0] # 如果不是英文 if title_lang != 'en': # 翻译为英文 translated_title = translator.translate(str(df.loc[i, 'title']), src=title_lang, dest='en').text df.loc[i, 'title'] = translated_title # 识别abs列的语言 abs_lang = lang_detector.classify(str(df.loc[i, 'abs']))[0] # 如果不是英文 if abs_lang != 'en': # 翻译为英文 translated_abs = translator.translate(str(df.loc[i, 'abs']), src=abs_lang, dest='en').text df.loc[i, 'abs'] = translated_abs # 将结果保存到新的Excel文件中 df.to_excel('2.xlsx', index=False) 这段代码的结果2.xlsx是空的
时间: 2024-04-15 17:30:33 浏览: 175
如果生成的2.xlsx文件是空的,可能是由于以下几个原因:
1. 检查1.xlsx文件是否存在,并且确保它包含了title和abs列的数据。
2. 确保你已经安装了所需的库,如pandas、langid和googletrans。你可以使用pip命令来安装它们:
```bash
pip install pandas langid googletrans==4.0.0-rc1
```
请注意,我们指定了googletrans的版本为4.0.0-rc1,因为在最新版本中,Google已经更改了API的使用方式,可能与示例代码不兼容。
3. 检查你的网络连接是否正常,因为示例代码中使用了Google Translate API进行翻译。
如果你仍然遇到问题,请尝试在代码中添加一些调试输出,以检查是否能正确识别语言和翻译内容。例如,你可以在循环中添加以下代码来输出识别和翻译的结果:
```python
print(f"Original title: {df.loc[i, 'title']}, Detected language: {title_lang}")
print(f"Original abs: {df.loc[i, 'abs']}, Detected language: {abs_lang}")
print(f"Translated title: {translated_title}")
print(f"Translated abs: {translated_abs}")
```
这样你就可以检查每个单元格的识别和翻译结果是否正确。如果仍然存在问题,请提供更多的信息和示例数据,以便我们更好地帮助你解决问题。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)