JSON形式の(多言語ファイル)一括翻訳 | python3Xのブログ

python3Xのブログ

ここでは40代、50代の方が日々の生活で役に立つ情報や私の趣味であるプログラム、Excelや科学に関する内容で投稿する予定です。

CSV形式からJSON形式への変換

----------------------------------------------------

csv_to_json.py

import json
import csv
json_list = []
keys = (
'Date', 'Name', 'Text')    # 列数と要素数を一致させる
# CSV ファイルの読み込み
with open('trans_in.csv', 'r', encoding="utf8") as f:
   
for row in csv.DictReader(f, keys):
        json_list.append(row)
# JSON ファイルへの書き込み
with open('trans_in.json', 'w') as f:
    json.dump(json_list, f)
# JSONファイルのロード
with open('trans_in.json', 'r', encoding="utf-8") as f:
    json_output = json.load(f)
    print(json_output)
-------------------------------------------------------
JSONファイルを翻訳するコード
trans_json.py
import boto3
import json
# リージョンを指定し、Translateサービスクライアントを作成する
translate = boto3.client('translate', 'us-east-2')
# 入力(JSON)ファイルを開く
with open('trans_in.json', 'r', encoding="utf-8") as file_in:
    reviews = json.load(file_in)   # JSONファイルを読み込む
# レビューを1件ずつ処理する
for review in reviews:
    result = translate.translate_text(
        Text=review[
'Text'],                # 本文を翻訳する
        SourceLanguageCode='auto', TargetLanguageCode='ja')
    review['Text'] = result['TranslatedText']     # 本文を翻訳結果に置き換える
# 出力(JSON)ファイルの準備をする
with open('trans_out.json', 'w', encoding="utf-8") as file_out:
    json.dump(reviews, file_out, indent=4, ensure_ascii=False) 
#  ファイルを書き込む
# JSONファイルのロード
with open('trans_out.json', 'r', encoding="utf-8") as f:
    json_output = json.load(f)
   
print(json_output)
----------------------------------------------------------