使用googletrans 只翻译英文不翻译链接,输出英文加链接
时间: 2024-03-11 07:45:51 浏览: 14
Sure, I can help you with that. Here's an example code snippet in Python that uses the `googletrans` library to translate English text but ignore links in the text:
```python
from googletrans import Translator
import re
# Define a regular expression pattern to match URLs
url_pattern = re.compile(r'http\S+')
# Define the English text with links
english_text = "This is a test text with a link to https://google.com"
# Remove the links from the text
text_without_links = url_pattern.sub('', english_text)
# Initialize the translator
translator = Translator()
# Translate the text without links
translation = translator.translate(text_without_links, dest='es')
# Combine the translated text with the original links
translated_text = url_pattern.sub('', translation.text) + " " + url_pattern.findall(english_text)[0]
# Print the translated text
print(translated_text)
```
In this code, we first define a regular expression pattern to match URLs in the text. We then remove any links from the English text using the `sub` method of the regular expression. Next, we initialize the translator and use it to translate the text without links to Spanish. Finally, we combine the translated text with the original links using the `findall` method of the regular expression and print the result.
Note that this code assumes that there is only one link in the text and that it is in the form of a URL starting with "http". If your links have a different format, you may need to adjust the regular expression pattern accordingly.