|
1 | | -""" |
2 | | -googletrans-python |
3 | | -""" |
4 | 1 | import re |
5 | 2 | import html |
6 | 3 | import urllib.request |
7 | 4 | import urllib.parse |
8 | 5 |
|
9 | | -__version__ = '0.1.0.0' |
| 6 | +__version__ = "0.2.0" |
| 7 | + |
| 8 | +def translate(to_translate: str, to_language: str = "auto", from_language: str = "auto") -> str: |
| 9 | + """ |
| 10 | + Translates a text from one language to another using the Google Translate API. |
| 11 | +
|
| 12 | + Args: |
| 13 | + to_translate (str): The text to translate. |
| 14 | + to_language (str, optional): The language to translate the text to. Defaults to "auto". |
| 15 | + from_language (str, optional): The language of the text to translate. Defaults to "auto". |
| 16 | +
|
| 17 | + Returns: |
| 18 | + str: The translated text. |
| 19 | + """ |
| 20 | + link = f"http://translate.google.com/m?tl={to_language}&sl={from_language}&q={urllib.parse.quote(to_translate)}" |
| 21 | + request = urllib.request.Request(link, headers={ |
| 22 | + 'User-Agent': "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1;.NET CLR 1.1.4322;.NET CLR 2.0.50727;.NET CLR 3.0.04506.30)"}) |
| 23 | + re_result = re.findall( |
| 24 | + r'(?s)class="(?:t0|result-container)">(.*?)<', urllib.request.urlopen(request).read().decode("utf-8")) |
| 25 | + return "" if len(re_result) == 0 else html.unescape(re_result[0]) |
10 | 26 |
|
11 | | -def translate(to_translate, to_language="auto", from_language="auto"): |
12 | | - link = f"http://translate.google.com/m?tl={to_language}&sl={from_language}&q={urllib.parse.quote(to_translate)}" |
13 | | - request = urllib.request.Request(link, headers={'User-Agent':"Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1;.NET CLR 1.1.4322;.NET CLR 2.0.50727;.NET CLR 3.0.04506.30)"}) |
14 | | - re_result = re.findall(r'(?s)class="(?:t0|result-container)">(.*?)<', urllib.request.urlopen(request).read().decode("utf-8")) |
15 | | - return "" if len(re_result) == 0 else html.unescape(re_result[0]) |
16 | 27 |
|
17 | 28 | if __name__ == "__main__": |
18 | | - print(translate("Hello, My name is python.", "ko")) |
| 29 | + print(translate("Hello, my name is Python.", "ko")) |
| 30 | + |
0 commit comments