CSV形式からJSON形式への変換
----------------------------------------------------
csv_to_json.py
import json
import csv
import csv
json_list = []
keys = ('Date', 'Name', 'Text') # 列数と要素数を一致させる
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)
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)
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)
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
result = translate.translate_text(
Text=review['Text'], # 本文を翻訳する
SourceLanguageCode='auto', TargetLanguageCode='ja')
json.dump(reviews, file_out, indent=4, ensure_ascii=False) # ファイルを書き込む
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)
with open('trans_out.json', 'r', encoding="utf-8") as f:
json_output = json.load(f)
print(json_output)
----------------------------------------------------------