You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.8(Windows 8)生成指定JSON结构的代码错误排查求助

Fixing Your JSON Generation Code for Python 3.8 on Windows 8

Hey there! Let's break down the issues in your code and fix them to match the target JSON structure you need.

Key Problems in Your Current Code

  • Reusing the same tmpel dictionary: You defined tmpel outside the sentence-processing loop, so every word update overwrites the same dictionary instead of creating a fresh one for each sentence's elements.
  • Missing spaces in key names: Your target uses elements 1 (with a space) but your code generates elements1 (no space). There's also inconsistent sentence/phrase naming to match your target.
  • Incorrect word index range: range(1, len(tmpliste)) stops one index short—for a 2-word phrase, this only processes the first word, leaving the second out.
  • Unfiltered empty strings: Your input ends with a ., so splitting creates an empty string at the end of the list, leading to invalid empty entries.
  • Mismatched word key formatting: Your target uses word1 (no space) for the first element set and word X (with space) for others, but your code doesn't account for this.

Corrected Code

import json

sent = "Lorem Ipsum. has been long time. It has. popularised."

def jsoncreator(strr):
    myJSON = {"datas": []}
    elements = {}
    # Split and clean: remove empty strings and strip extra whitespace
    tmp = [segment.strip() for segment in strr.split(".") if segment.strip()]
    
    for content, idx in zip(tmp, range(1, len(tmp)+1)):
        # Match target's sentence/phrase naming
        if idx <= 2:
            text_key = f"sentence {idx}"
        else:
            text_key = f"phrase {idx}"
        elements[text_key] = content
        
        elements[f"elements {idx}"] = []
        tmpel = {}  # Create a new word dict for each entry
        words = content.split()
        
        # Loop through all words with correct indexing
        for word, word_idx in zip(words, range(1, len(words)+1)):
            # Match target's word key format
            if idx == 1:
                word_key = f"word{word_idx}"
            else:
                word_key = f"word {word_idx}"
            tmpel[word_key] = word
        
        elements[f"elements {idx}"].append(tmpel)
    
    myJSON['datas'].append(elements)
    # Print formatted JSON for readability
    print(json.dumps(myJSON, indent=2))
    return myJSON

jsoncreator(sent)

What This Fixes

  1. Resets tmpel per sentence: Ensures each elements X entry gets its own unique word dictionary.
  2. Cleans split results: Removes empty strings and extra whitespace to avoid invalid entries.
  3. Matches target key names: Uses sentence X for the first two entries and phrase X for the rest, plus adds the required space in elements X.
  4. Correct word indexing: Uses range(1, len(words)+1) to capture every word in the phrase.
  5. Aligns word key formatting: Exact match for your target's word1 (no space) and word X (with space) patterns.

Output (Matches Your Target)

{
  "datas": [
    {
      "sentence 1": "Lorem Ipsum",
      "elements 1": [
        {
          "word1": "Lorem",
          "word2": "Ipsum"
        }
      ],
      "sentence 2": "has been long time",
      "elements 2": [
        {
          "word 1": "has",
          "word 2": "been",
          "word 3": "long",
          "word 4": "time"
        }
      ],
      "phrase 3": "It has",
      "elements 3": [
        {
          "word 1": "It",
          "word 2": "has"
        }
      ],
      "phrase 4": "popularised",
      "elements 4": [
        {
          "word 1": "popularised"
        }
      ]
    }
  ]
}

内容的提问来源于stack exchange,提问作者Laz22434

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 17:47:40