#症状
Python3上で,pyocr(Tesseract OCR)を使用して、OCRで抽出した文字を、有償のCloud Translation APIでGoogle翻訳するプログラムを生成してます。OCRの結果をPrint文で表示したところ、文章の折り返し部分で改行されて表示されます。
しかし、その結果をCloud Translation APIでGoogle翻した結果をprint文で表示したところ、改行が反映されず、一文として表示されてしまいます。
#講じた対策
LineBoxBuilderを使用して、元の文章を一行ずつ抽出し、配列に格納し、そこから順番に取り出して翻訳してみたのですが、それだと、二行以上にまたいでいる文章が、1行ごとに分裂するため、きちんと翻訳することができません。
###症状発生時のソースコード
Python3
1# Imports the Google Cloud client library 2from google.cloud import translate 3import pyocr 4import sys 5from PIL import Image 6# Instantiates a client 7def ocr(): 8 tools = pyocr.get_available_tools() 9 if len(tools) == 0: 10 print("No OCR tool found") 11 sys.exit(1) 12# The tools are returned in the recommended order of usage 13 tool = tools[0] 14 15 lang = "eng"##元の言語の指定 16 print("解析中") 17 builder_t = pyocr.builders.TextBuilder()#テキスト全体を所得 18 ocr = tool.image_to_string( 19 Image.open('psoc_clip.png'), 20 lang=lang, 21 builder = builder_t 22 ) 23 return ocr 24def Trans(ocr): 25 26 translate_client = translate.Client() 27 28 # The text to translate 29 # The target language 30 target = 'ja' 31 32 # Translates some text into Russian 33 translation = translate_client.translate( 34 ocr, 35 target_language=target) 36 37 print(u'Text: {}'.format(ocr)) 38 print("\n") 39 print(u'Translation: {}'.format(translation['translatedText'])) 40def main(): 41 txt = ocr() 42 Trans(txt) 43main()
##結果
Text: Functional Definition CPU and Memory Subsystem cpu ‘The Cortex-MO CPU in PSoC 4200 is part of the 32-bit MCU ‘subsystem, which is optimized for low-power operation with ‘extensive clock gating. It mostly uses 16-bit instructions and ‘executes a subset of the Thumb-2 instruction set. This enables fully compatible binary upward migration of the code to higher performance processors such as the Cortex-M3 and M4, thus ‘enabling upward compatibility. The Cypress implementation includes a hardware multiplier that provides a 32-bit result in one ‘cycle. It includes a nested vectored interrupt controller (NVIC) block with 32 interrupt inputs and also includes a Wakeup Interrupt Controller (WIC). The WIC can wake the processor up from the Deep Sleep mode, allowing power to be switched off to the main processor when the chip is in the Deep Sleep mode. ‘The Cortex-MO CPU provides a Non-Maskable Interrupt (NMI) input, which is made available to the user when itis not in use for system functions requested by the user. Translation: 機能定義CPUおよびメモリサブシステムcpu PSoC 4200のCortex-MO CPUは、32ビットMCUサブシステムの一部です。これは、広範なクロックゲーティングを備えた低電力動作用に最適化されています。これは主に16ビット命令を使用し、Thumb-2命令セットのサブセットを実行します。これにより、Cortex-M3やM4などの高性能プロセッサへのコードの完全互換バイナリ上位移行が可能になり、したがって上位互換が可能になります。サイプレスの実装には、1サイクルで32ビットの結果を提供するハードウェア乗算器が含まれています。 32個の割り込み入力を持つネスト型ベクトル割り込みコントローラー(NVIC)ブロックと、ウェイクアップ割り込みコントローラー(WIC)も含まれています。 WICはプロセッサをディープスリープモードから復帰させることができ、チップがディープスリープモードのときにメインプロセッサへの電源をオフにすることができます。 'Cortex-MO CPUは、マスク不可能割り込み(NMI)入力を提供します。これは、ユーザーが要求したシステム機能に使用されていないときにユーザーが利用できるようにします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。