pythonでコメントを英訳

#pythonで日本語コメントを英語化
コーディングした後に、コメントを日本語化してほしいと依頼があった
ファイル数も多く１件ずつgoogle翻訳するのも大変なので、pythonでやっちまったな


※pythonのコーディング規約pep8なら使えると思う


#### main.py
```
#!/usr/bin/env python
# -*- coding: utf8 -*-

import form

if __name__ == "__main__":
    root = form.tk.Tk()
    root.title(u"Comment Translator For Python")
    app = form.Application(master=root)
    app.mainloop()
    pass
```
#### form.py
```
import sys
import tkinter as tk
import tkinter.scrolledtext
import tkinter.filedialog
import translator as tr
import glob
import Util
import threading

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack(expand=1, fill=tk.BOTH, anchor=tk.NW)
        self.__create_widgets()
        self.__IsCancelTranslate = False
        self.__initialMessage()
        
    def __create_widgets(self):
        self.label = tk.Label(self, text=u'対象フォルダ')
        self.label2 = tk.Label(self, text=u'出力フォルダ')
        self.button = tk.Button(self, text=u'開く', command=self.__button_click)
        self.button2 = tk.Button(self, text=u'開く', command=self.__button2_click)
        self.button3 = tk.Button(self, text=u'開始', command=self.__button3_translateStart)
        self.entry = tk.Entry(self)
        self.entry2 = tk.Entry(self)
        self.scrolledText = tk.scrolledtext.ScrolledText(self)

        self.label.grid(column=0, row=0, sticky=tk.W)
        self.label2.grid(column=0, row=1, sticky=tk.W)
        self.button.grid(column=3, row=0, sticky=tk.E)
        self.button2.grid(column=3, row=1, sticky=tk.E)
        self.button3.grid(column=4, row=0, rowspan=2, sticky=tk.E)
        self.entry.grid(column=1, columnspan=2, row=0, sticky=tk.EW)
        self.entry2.grid(column=1, columnspan=2, row=1, sticky=tk.EW)
        self.scrolledText.grid(column=0, columnspan=5, row=2, sticky=tk.NSEW)

        self.columnconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)
        
    def __initialMessage(self):
        self.__WriteLog("翻訳対象と翻訳結果出力先フォルダを指定して開始ボタンを押下して下さい")
        self.__WriteLog("入力チェック作ってないので翻訳対象は手打ちしないでください")

    # 対象フォルダの開くボタン
    def __button_click(self):
        dir = 'C:\\'
        fle = tk.filedialog.askdirectory(initialdir = dir)
        if fle:
            self.entry.delete(0, tk.END)
            self.entry.insert(0, fle)

    # 翻訳先フォルダの開くボタン
    def __button2_click(self):
        dir = 'C:\\'
        fle = tk.filedialog.askdirectory(initialdir = dir)
        if fle:
            self.entry2.delete(0, tk.END)
            self.entry2.insert(0, fle)

    def __button3_translateStart(self):
        if not self.entry.get():
            self.__WriteLog("翻訳対象の入力がありません")
            return
        if not self.entry2.get():
            self.__WriteLog("翻訳出力先の入力がありません")
            return

        self.__WriteLog("Start Translation: 完了メッセージが表示されるまで閉じないでください")
        self.__IsCancelTranslate = False

        threading.Thread(target=self.__translateFiles).start()
        
        self.button3 = tk.Button(self, text=u'中断', command=self.__button3_translateCancel)
        self.button3.grid(column=4, row=0, rowspan=2, sticky=tk.E)
        
    def __button3_translateCancel(self):
        self.__IsCancelTranslate = True
        
        self.button3 = tk.Button(self, text=u'開始', command=self.__button3_translateStart)
        self.button3.grid(column=4, row=0, rowspan=2, sticky=tk.E)

    def __translateFiles(self):
        targetDirectry = self.entry.get()
        translatedDirectry = self.entry2.get()

        pyFiles = glob.glob(f"{targetDirectry}\\**\\*.py", recursive=True)
        pyFilesLength = len(pyFiles)

        # . + (絶対パス - 指定パス) = 指定パスからの相対パス(.\relativPath.py)
        directryNameLength = len(targetDirectry)
        relativPaths = ["." + n[directryNameLength:] for n in pyFiles]

        for (file, relativPath, i) in zip(pyFiles, relativPaths, range(0, pyFilesLength)):
            translator = tr.translator(file)
            translatedLines = translator.translate()
            if self.__IsCancelTranslate:
                self.__WriteLog("処理を中断しました。")
                break

            translatedText = '\n'.join(translatedLines)
            filename = translatedDirectry + relativPath[1:]

            Util.writeText(translatedText, filename)
            progress = round((i + 1) / pyFilesLength * 100)
            msg = f"{progress}% Translated \"{relativPath}\""
            self.__WriteLog(msg)
            
        self.button3 = tk.Button(self, text=u'開始', command=self.__button3_translateStart)
        self.button3.grid(column=4, row=0, rowspan=2, sticky=tk.E)
        self.__WriteLog("Finish!: 閉じても大丈夫です！")
    
    def __WriteLog(self, msg):
        self.scrolledText.insert(tk.END, f"{msg}\n")
```
#### translator.py
```
from googletrans import Translator

class translator:

    def __init__(self, filePath):
        # File open
        self.__source = open(filePath, 'r+', encoding = "utf-8")
        self.text = self.__source.read()
        self.__source.close
        
        self.lines = self.text.split('\n')
        self.lineCount = self.lines.count
        
        # f = open('Sample\\honyaku.py', 'r+',encoding="utf-8_sig")
    def translate(self):
        translator = Translator(from_lang = "ja", to_lang = "en")
        translatedLines = []
        for line in self.lines:
            translatedLine = ""
            # クォーテーションとダブルクォーテーションの中であるか
            isInQuotation = isInDoubleQuotation = False
            for i, char in enumerate(line):
                if char == '\'':
                    isInQuotation = not isInQuotation 
                if char == '\"':
                    isInDoubleQuotation = not isInDoubleQuotation
                if char != '#':
                    continue
                if isInQuotation or isInDoubleQuotation:
                    continue
                
                lineLength = len(line)
                comment = line[i + 2: lineLength]
                translatedComment = translator.translate(comment)
                translatedLine = line + f" ({translatedComment})"
                
                break
            if translatedLine:
                translatedLines.append(translatedLine)
            else:
                translatedLines.append(line)

        return(translatedLines)
```
####Util.py
```
import os
import os.path
def writeText(text, filename):
    directry = os.path.dirname(filename)
    if not os.path.exists(directry):
        os.makedirs(directry)
    f = open(filename,'w', encoding='utf-8')
    f.write(text)
    f.close()
```

利用制限とかあるからずっと使えないけど、フォルダ単位でできるからOK