Advertisement
MeowalsoMeow

oneline_translator_final_stage

Nov 5th, 2021
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.72 KB | None | 0 0
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import sys
  4. import argparse
  5.  
  6.  
  7. class OnlineTranslator:
  8. def __init__(self):
  9. self.languages = {
  10. '1': 'arabic',
  11. '2': 'german',
  12. '3': 'english',
  13. '4': 'spanish',
  14. '5': 'french',
  15. '6': 'hebrew',
  16. '7': 'japanese',
  17. '8': 'dutch',
  18. '9': 'polish',
  19. '10': 'portuguese',
  20. '11': 'romanian',
  21. '12': 'russian',
  22. '13': 'turkish'
  23. }
  24. self.log = []
  25. self.language_1 = ''
  26. self.language_2 = ''
  27. self.word = ''
  28. self.temp_lang2 = ''
  29. self.s = requests.Session()
  30. self.example_num = 1
  31.  
  32. def ask_languages(self):
  33. print("Hello, you're welcome to the translator. Translator supports:")
  34. for k, v in self.languages.items():
  35. print(f'{k}. {v.capitalize()}')
  36. self.language_1 = input('Type the number of your language:\n')
  37. self.language_2 = input(
  38. "Type the number of a language you want to translate to or '0' to translate to all languages:\n")
  39. self.temp_lang2 = self.language_2
  40. self.word = input('Type the word you want to translate:\n')
  41.  
  42. def print(self, *strings):
  43. for string in strings:
  44. self.log.append(string + '\n')
  45. print(string)
  46.  
  47. def input(self, message=''):
  48. if message != '':
  49. self.print(message)
  50. term = input()
  51. self.log.append(term + '\n')
  52. return term
  53.  
  54. def translate(self, l2):
  55. if self.language_1 == l2:
  56. return
  57. url = f'https://context.reverso.net/translation/{self.language_1}-{l2}/{self.word}'
  58. headers = {'User-Agent': 'Mozilla/5.0'}
  59. r = self.s.get(url, headers=headers)
  60. soup = BeautifulSoup(r.content, 'html.parser')
  61. # only works in terminal words = soup.find('div', {'id': 'translations-content'}).find_all('a', {'class': 'translation'})
  62. # only works in terminal words = soup.find_all('a', class_='translation')
  63. # only works in terminal words = soup.find_all('a', {'class': 'translation'})
  64. words = soup.find('div', {'id': 'translations-content'})
  65. words_list = [w.text.strip() for w in words if len(w.text.strip()) > 0]
  66. self.print(f'{l2.capitalize()} Translations:')
  67. for w in range(self.example_num):
  68. self.print(words_list[w])
  69. self.print(f'\n{l2.capitalize()} Examples:')
  70. lan1_examples = soup.find('section', {'id': 'examples-content'}).find_all('div', {'class': 'src'})
  71. lan2_examples = soup.find('section', {'id': 'examples-content'}).find_all('div', {'class': 'trg'})
  72. lan1_list = [e.text.strip() for e in lan1_examples if len(e.text.strip()) > 0]
  73. lan2_list = [e.text.strip() for e in lan2_examples if len(e.text.strip()) > 0]
  74. for x in range(self.example_num):
  75. self.print(lan1_list[x])
  76. self.print(lan2_list[x] + '\n')
  77.  
  78. def find_key(self, value):
  79. for _k in self.languages.keys():
  80. if value == self.languages[_k]:
  81. return _k
  82.  
  83. def args(self):
  84. parser = argparse.ArgumentParser()
  85. parser.add_argument('language1')
  86. parser.add_argument('language2')
  87. parser.add_argument('word')
  88. args = parser.parse_args()
  89. self.temp_lang2 = args.language2
  90. self.language_1 = self.find_key(args.language1)
  91. self.language_2 = self.find_key(args.language2) if args.language2 != 'all' and args.language2 != '0' else '0'
  92. self.word = args.word
  93.  
  94. def operate(self):
  95. try:
  96. self.language_1 = self.languages[self.language_1]
  97. if self.language_2 != 'all' and self.language_2 != '0':
  98. self.language_2 = self.languages[self.language_2]
  99. self.translate(self.language_2)
  100. else:
  101. for x in range(len(self.languages)):
  102. self.translate(self.languages[f'{x + 1}'])
  103. with open(f'{self.word}.txt', 'w', encoding='utf-8') as file:
  104. for x in self.log:
  105. file.write(x)
  106. except requests.exceptions.ConnectionError:
  107. print('Something wrong with your internet connection')
  108. except KeyError:
  109. print(f"Sorry, the program doesn't support {self.temp_lang2}")
  110. except TypeError:
  111. print(f'Sorry, unable to find {self.word}')
  112.  
  113. def start(self):
  114. if len(sys.argv) == 4:
  115. self.args()
  116. self.operate()
  117. else:
  118. self.ask_languages()
  119. self.operate()
  120.  
  121.  
  122. translator = OnlineTranslator()
  123. translator.start()
  124.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement