如何从文本文件中提取键和值

How to extract key and value from a text file

我想从现有文本文件中提取键和值。在单独的变量中键入,在单独的变量中键入值。

文本文件(sample.txt)包含以下内容,

one:two
three:four
five:six
seven:eight
nine:ten
sample:demo

我可以从文本文件中读取内容,但无法继续提取键和值。

with open ("sampletxt.txt", "r") as hfile:
    sp = hfile.read()
    print (sp)

x=0
for line in sp:
    sp.split(":")[x].strip()
    x+=1

以上只提取了值,最后还提供了index out of range异常

If we iterate through the file, i am expecting the output as below,

Key 0 = one
Key 1 = three
Key 2 = five
Key 3 = seven
key 4 = sample

Value 0 = two
Value 1 = four
Value 2 = six
Value 3 = eight
Value 4 = ten

你为什么不试试:

with open ("sampletxt.txt", "r") as hfile:
    sp = hfile.read()
    print (sp)

dictionary = {}
for x, line in enumerate(sp):
    line_list = sp.split(":")
    dictionary[line_list[0]]=line_list[1]

这应该有效:

with open ("sampletxt.txt", "r") as hfile:
  sp = hfile.read()
  print (sp)

lines = sp.split("\n")
for line in lines:
  # print("line:[{0}]".format(line))
  parts = line.split(":")
  print("key:[{0}], value:[{1}]".format(parts[0], parts[1]))

它可以工作:

sp = open ("sampletxt.txt", "r")
x=0
key=[]
value=[]
try:
    while True:
        text_line = sp.readline()
        if text_line:
            text_line = ''.join(text_line)
            text_line = text_line.split()
            text_line = ''.join(text_line).split(':')
            key.append(text_line[0])
            value.append(text_line[1])
            x += 1
        else:
            for i in range(x):
                print("Key {} = {}".format(i,key[i]))
            print("")
            for i in range(x):
                print("Value {} = {}".format(i,value[i]))
            break
finally:
    sp.close()

输出为:

Key 0 = one
Key 1 = three
Key 2 = five
Key 3 = seven
Key 4 = nine
Key 5 = sample

Value 0 = two
Value 1 = four
Value 2 = six
Value 3 = eight
Value 4 = ten
Value 5 = demo

这与您的要求相似

在使用索引之前,您应该始终检查 split returns 两个成员(或您期望的任何数量)