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

如何从文本文件中分割冒号分隔的键值对?解决单行多键值对分割失败问题

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:

  1. Dictionary initialization: I added myvars = {} upfront—your original code would throw a NameError without this, since the dictionary wasn't created before assigning to it.
  2. Full line splitting: Instead of partition, we use split(": ") to break the entire line into a list of segments. For example, the line Name: John: DoB: 01-01-2000 becomes ["Name", "John", "DoB", "01-01-2000"].
  3. 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).
  4. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:12:40