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
tmpeldictionary: You definedtmpeloutside 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 generateselements1(no space). There's also inconsistentsentence/phrasenaming 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 andword 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
- Resets
tmpelper sentence: Ensures eachelements Xentry gets its own unique word dictionary. - Cleans split results: Removes empty strings and extra whitespace to avoid invalid entries.
- Matches target key names: Uses
sentence Xfor the first two entries andphrase Xfor the rest, plus adds the required space inelements X. - Correct word indexing: Uses
range(1, len(words)+1)to capture every word in the phrase. - Aligns word key formatting: Exact match for your target's
word1(no space) andword 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
相关产品推荐
相关产品推荐

