Skip to content

Instantly share code, notes, and snippets.

@oldherl
Created August 19, 2019 07:36
Show Gist options
  • Save oldherl/5e9b571c85818103dcc5b5ab28d5848a to your computer and use it in GitHub Desktop.
Save oldherl/5e9b571c85818103dcc5b5ab28d5848a to your computer and use it in GitHub Desktop.
Google Translate comments in C/C++ source code (to English by default) from clipboard
from comment_parser import comment_parser as cmp
from googletrans import Translator as Tr
# pip install ansicolors
from colors import color
def print_item(item):
print(color("Original (%s):" % item.src, fg="red", style="underline+bold"))
print(item.origin)
print(color("Translated (%s):" % item.dest, fg="green", style="underline+bold"))
print(item.text)
def extract_and_translate(code, destlang='en', srclang='auto'):
try:
cc = cmp.extract_comments_from_str(code, mime='text/x-c++')
except:
cc = []
tr = Tr(service_urls=['translate.google.cn'])
if cc:
dd = []
last_sl_ln = -999
for c in cc:
ln = c.line_number()
s = c.text()
m = c.is_multiline()
if m:
dd += [ln, s],
last_sl_ln = -999
else:
if last_sl_ln + 1 == ln:
dd[-1][1] += " " + s
else:
dd += [ln, s],
last_sl_ln = ln
for d in dd:
ln = d[0]
s = d[1]
tr_res = tr.translate(s, dest=destlang, src=srclang)
print(color("Line %d:" % ln, fg="blue", style="bold"))
print_item(tr_res)
else:
print("No comment found. Translating the whole text.")
tr_res = tr.translate(code, dest=destlang, src=srclang)
print_item(tr_res)
def get_clipboard():
import tkinter
root = tkinter.Tk()
root.withdraw()
text = root.clipboard_get()
root.destroy()
return text
# These two lines are for ANSI escape chars on Windows
import os
os.system('color')
#extract_and_translate("// Noch unschöne Lösung...")
#extract_and_translate("Noch unschöne Lösung...")
extract_and_translate(get_clipboard())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment