如何从文本文件中分割冒号分隔的键值对?解决单行多键值对分割失败问题
Fixing Key-Value Pair Parsing When Multiple Pairs Exist on a Single Line
I get your problem right away—your current code only works when there's one key: value pair per line. If a line has multiple colon-separated pairs (like Name: John: DoB: 01-01-2000: Gender: M), the partition(": ") method only grabs the first key, and shoves everything else into a single value. That's definitely not what you want.
Here's a revised version of your code that handles multiple key-value pairs in a single line correctly:
# Initialize the dictionary to store your key-value pairs myvars = {} with open("textfile.txt", "r+") as myfile: for line in myfile: # Strip whitespace from the line, split by ": ", and filter out empty segments parts = [segment.strip() for segment in line.strip().split(": ") if segment.strip()] # Iterate through the segments in pairs (key at even index, value at odd) for idx in range(0, len(parts), 2): # Make sure we don't hit an index error if the line ends with a stray colon if idx + 1 < len(parts): key = parts[idx] value = parts[idx + 1] myvars[key] = value # Print in your desired format print(f"|{key} {value} |")
Key improvements explained:
- Dictionary initialization: I added
myvars = {}upfront—your original code would throw aNameErrorwithout this, since the dictionary wasn't created before assigning to it. - Full line splitting: Instead of
partition, we usesplit(": ")to break the entire line into a list of segments. For example, the lineName: John: DoB: 01-01-2000becomes["Name", "John", "DoB", "01-01-2000"]. - Pair-wise iteration: Using a loop with a step of 2 lets us grab each key (at even indices) and its corresponding value (at the next odd index).
- Boundary check: The
if idx + 1 < len(parts)line prevents crashes if a line ends with an extra colon (leaving an unmatched key at the end of the segment list).
Example output
If your input file has lines like:
Name: John: DoB: 01-01-2000 Gender: M: Country: USA State: CA: Profession: Engineer
The code will output exactly what you're expecting:
|Name John | |DoB 01-01-2000 | |Gender M | |Country USA | |State CA | |Profession Engineer |
内容的提问来源于stack exchange,提问作者Tara D
相关产品推荐
相关产品推荐

