Skip to main content
 首页 » 编程设计

python之如何检索两个字符串之间的值

2025年05月04日2452php

我有一个 json 文件。我想使用 python 检索两个字符串之间的值。

{ 
    "101": { 
 
        "set": [ 
            "1012",  
            "some text a." 
        ],  
        "tag": "tagtext" 
    },  
    "1027": { 
        "slide": [ 
            "1013757",  
            "x" 
        ] 
    },  
    "1014220": { 
        "set": [ 
            "1018420",  
            "some text." 
        ],  
        "ans": "4th" 
    },  
    "1019660": { 
        "set": [ 
            "1031920",  
            "Some text b" 
        ],  
        "tag": "tagtext" 
    },  
    "1034280": { 
        "set": [ 
            "1040560",  
            "some text" 
        ],  
        "interact": "intertext" 
    }, 

我想提取set和tag之间的数据:

输出应该是: “一些文字。” “一些文本 b。”

请您参考如下方法:

将输入解析为 JSON 并检查是否存在 标签。

import json 
 
with open("j.json") as f: 
    j = json.load(f) 
 
for k, v in j.items(): 
    try: 
        s = v["set"] 
        t = v["tag"] 
        print(s[1]) 
    except: 
        # no tag 
        pass 

输出:

some text a. 
Some text b