如何使用python快速翻译json文件

问题:

如何使用python快速翻译json文件

如何使用python快速翻译json文件

思路:

  • 因为json格式类似python的dict类型,是否能通过翻译键值对的方法将字典key对应的value配合有道翻译api进行逐个翻译呢?

  • 想法是有了,但是无从下手:sob: :joy: 希望大佬指点!

Code:

import requests
import json

def youDaoApi(words):
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
    # 传输的参数,其中 i 为需要翻译的内容
    word = '\n'.join(words)
    key = {
        'i': words,
        'from': 'en',
        'to': 'zh-CHS',
        'smartresult': 'dict',
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTlME'
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
    }
    # key 这个字典为发送给有道词典服务器的内容
    response = requests.post(url, data=key, headers=headers)
    # 判断服务器是否相应成功
    if response.status_code == 200:
        # 然后相应的结果
        result = json.loads(response.text)

        # print(result)

        return [item[0]['tgt'] for item in result['translateResult']]

    else:
        print("有道词典调用失败")
        # 相应失败就返回空
        return None
Jason990420
最佳答案

以下采用正则式, 取出以字符串格式的json中, 所有非键值的字符串, 其结果可以在 replace 函数中经翻译再取代原字符串.

字典值后为 ,}, 列表值后为 ,]

注: 该正则式为简单定义, 某些特别情况会无法处理.

import re
import json

json_string = """
    {
        "squadName" : "Super hero squad",
        "homeTown" : "Metro City",
        "formed" : 2016,
        "secretBase" : "Super tower",
        "active" : true,
        "members" : [
            {
                "name" : "Molecule Man",
                "age" : 29,
                "secretIdentity" : "Dan Jukes",
                "powers" : [
                    "Radiation resistance",
                    "Turning tiny",
                    "Radiation blast"
                ]
            },
            {
                "name" : "Madame Uppercut",
                "age" : 39,
                "secretIdentity" : "Jane Wilson",
                "powers" : [
                    "Million tonne punch",
                    "Damage resistance",
                    "Superhuman reflexes"
                ]
            },
            {
                "name" : "Eternal Flame",
                "age" : 1000000,
                "secretIdentity" : "Unknown",
                "powers" : [
                    "Immortality",
                    "Heat Immunity",
                    "Inferno",
                    "Teleportation",
                    "Interdimensional travel"
                ]
            }
        ]
    }
""".strip()

regex = re.compile(r'''
    "[^"]+?"            # "..." string, not include "..."..."
    (?=                 # Must end with
        \s*?            # Some whitespace
        [,\]\}]         # and `,`, `]` or `}`
    )
''', re.VERBOSE | re.MULTILINE)

def replace(match):
    return match.group().upper()

result = regex.sub(replace, json_string)
print(result)

代码中 replace 将字符串转换成大写, 可自行更换为翻译结果.

{
        "squadName" : "SUPER HERO SQUAD",
        "homeTown" : "METRO CITY",
        "formed" : 2016,
        "secretBase" : "SUPER TOWER",
        "active" : true,
        "members" : [
            {
                "name" : "MOLECULE MAN",
                "age" : 29,
                "secretIdentity" : "DAN JUKES",
                "powers" : [
                    "RADIATION RESISTANCE",
                    "TURNING TINY",
                    "RADIATION BLAST"
                ]
            },
            {
                "name" : "MADAME UPPERCUT",
                "age" : 39,
                "secretIdentity" : "JANE WILSON",
                "powers" : [
                    "MILLION TONNE PUNCH",
                    "DAMAGE RESISTANCE",
                    "SUPERHUMAN REFLEXES"
                ]
            },
            {
                "name" : "ETERNAL FLAME",
                "age" : 1000000,
                "secretIdentity" : "UNKNOWN",
                "powers" : [
                    "IMMORTALITY",
                    "HEAT IMMUNITY",
                    "INFERNO",
                    "TELEPORTATION",
                    "INTERDIMENSIONAL TRAVEL"
                ]
            }
        ]
    }
2周前 评论
Scrooge (楼主) 2周前
Jason990420 (作者) 2周前
讨论数量: 3
Jason990420

以下采用正则式, 取出以字符串格式的json中, 所有非键值的字符串, 其结果可以在 replace 函数中经翻译再取代原字符串.

字典值后为 ,}, 列表值后为 ,]

注: 该正则式为简单定义, 某些特别情况会无法处理.

import re
import json

json_string = """
    {
        "squadName" : "Super hero squad",
        "homeTown" : "Metro City",
        "formed" : 2016,
        "secretBase" : "Super tower",
        "active" : true,
        "members" : [
            {
                "name" : "Molecule Man",
                "age" : 29,
                "secretIdentity" : "Dan Jukes",
                "powers" : [
                    "Radiation resistance",
                    "Turning tiny",
                    "Radiation blast"
                ]
            },
            {
                "name" : "Madame Uppercut",
                "age" : 39,
                "secretIdentity" : "Jane Wilson",
                "powers" : [
                    "Million tonne punch",
                    "Damage resistance",
                    "Superhuman reflexes"
                ]
            },
            {
                "name" : "Eternal Flame",
                "age" : 1000000,
                "secretIdentity" : "Unknown",
                "powers" : [
                    "Immortality",
                    "Heat Immunity",
                    "Inferno",
                    "Teleportation",
                    "Interdimensional travel"
                ]
            }
        ]
    }
""".strip()

regex = re.compile(r'''
    "[^"]+?"            # "..." string, not include "..."..."
    (?=                 # Must end with
        \s*?            # Some whitespace
        [,\]\}]         # and `,`, `]` or `}`
    )
''', re.VERBOSE | re.MULTILINE)

def replace(match):
    return match.group().upper()

result = regex.sub(replace, json_string)
print(result)

代码中 replace 将字符串转换成大写, 可自行更换为翻译结果.

{
        "squadName" : "SUPER HERO SQUAD",
        "homeTown" : "METRO CITY",
        "formed" : 2016,
        "secretBase" : "SUPER TOWER",
        "active" : true,
        "members" : [
            {
                "name" : "MOLECULE MAN",
                "age" : 29,
                "secretIdentity" : "DAN JUKES",
                "powers" : [
                    "RADIATION RESISTANCE",
                    "TURNING TINY",
                    "RADIATION BLAST"
                ]
            },
            {
                "name" : "MADAME UPPERCUT",
                "age" : 39,
                "secretIdentity" : "JANE WILSON",
                "powers" : [
                    "MILLION TONNE PUNCH",
                    "DAMAGE RESISTANCE",
                    "SUPERHUMAN REFLEXES"
                ]
            },
            {
                "name" : "ETERNAL FLAME",
                "age" : 1000000,
                "secretIdentity" : "UNKNOWN",
                "powers" : [
                    "IMMORTALITY",
                    "HEAT IMMUNITY",
                    "INFERNO",
                    "TELEPORTATION",
                    "INTERDIMENSIONAL TRAVEL"
                ]
            }
        ]
    }
2周前 评论
Scrooge (楼主) 2周前
Jason990420 (作者) 2周前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!