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

时间:2019-04-08 07:26:07

标签: python string parsing key-value

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

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

这如何在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行。输出将按键(第一列)排序。

代码启动器:

# 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(" ")
  .
  .
  ?

1 个答案:

答案 0 :(得分: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