将键多次值的字符串转换为键值对

问题描述 投票:0回答:1

我有一个以空格分隔的文本文件。每行包含一个项目,后跟零个或多个其他项目。所有值都是字符串。

我希望将数据输出为键值对。

如何在Python中完成?

输入:

1: 200
2:
3: 300 400 abc
4: xyz 300

期望的输出:

1: 200
2:
3: 300
3: 400
3: abc
4: xyz
4: 300

如果它更容易,可以从输出中省略第2行。输出将按键排序(第1列)。

代码启动器:

# Open the text file
file = open("data.txt", "r")

# Read each \n terminated line into a list called 'lines'
lines = file.readlines()

# Iterate through each line
for line in lines:
  # Remove leading/trailing spaces and newline character
  line = line.strip()

  # Split the line into list items (but the number varies with each line)
  .... = line.split(" ")
  .
  .
  ?
python string parsing key-value
1个回答
1
投票

使用简单的迭代。

例如:

result = []
with open(filename) as infile:
    for line in infile:                   #Iterate each line
        key, val = line.split(":")        #Get key-value
        for i in val.strip().split():
            result.append((key, i))

with open(filename, "w") as outfile:      #Write Output
    for line in result:
        outfile.write(": ".join(line) + "\n")  

输出:

1: 200
3: 300
3: 400
3: abc
4: xyz
4: 300
© www.soinside.com 2019 - 2024. All rights reserved.