如何使用googletrans 只翻译英文不翻译链接和标签
时间: 2024-03-10 08:46:23 浏览: 27
要使用 `googletrans` 包只翻译英文并忽略链接和标签的内容,可以先将文本中的链接和标签部分去除,然后再进行翻译。可以使用 Python 自带的 `re` 模块来实现去除链接和标签的功能。例如:
```python
import re
from googletrans import Translator
# 创建翻译器对象
translator = Translator(service_urls=['translate.google.cn'])
# 需要翻译的英文字符串
en_text = "Hello, <a href='https://www.example.com'>world</a>!"
# 去除链接和标签部分
text_without_tags = re.sub(r'<[^>]*>', '', en_text)
# 翻译英文部分
en_without_tags = re.sub(r'[^\w\s]', '', text_without_tags)
zh_text = translator.translate(en_without_tags, dest='zh-CN').text
print(zh_text) # 输出:你好,世界!
```
这里使用 `re.sub(r'<[^>]*>', '', en_text)` 将文本中的所有标签部分去除,得到不包含标签的文本内容。然后使用 `re.sub(r'[^\w\s]', '', text_without_tags)` 将文本中的所有非英文字符去除,得到只包含英文部分的文本内容。最后使用翻译器对象将英文部分翻译成中文。
需要注意的是,这种方法只适用于英文内容中包含链接和标签的情况,如果需要翻译其他语言的内容,或者需要保留链接和标签,需要修改正则表达式的匹配规则。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![](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)
![](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)