Python 以dict格式读取文本文件
我的文本文件如下..每行用空格分隔Python 以dict格式读取文本文件,python,python-3.x,Python,Python 3.x,我的文本文件如下..每行用空格分隔 dream 4.345 0.456 6.3456 play 0.1223 -0.345 5.3543 faster 1.324 2.435 -2.2345 我想写一份口述并打印如下 dream: [4.345 0.456 6.3456] play: [0.1223 -0.345 5.3543] faster: [1.324 2.435 -2.2345] 我的代码如下。请纠正我这个 with open("text.txt", "r") as file:
dream 4.345 0.456 6.3456
play 0.1223 -0.345 5.3543
faster 1.324 2.435 -2.2345
我想写一份口述并打印如下
dream: [4.345 0.456 6.3456]
play: [0.1223 -0.345 5.3543]
faster: [1.324 2.435 -2.2345]
我的代码如下。请纠正我这个
with open("text.txt", "r") as file:
for lines in file:
line = lines.split()
keys = b[0]
values = b[1:]
d[keys] = values
print d
对于python3,如果您希望获得所需的结果:
d = {}
with open("text.txt", "r") as file:
for lines in file:
line = lines.split()
keys = line[0]
values = list(map(float, line[1:]))
d[keys] = values
for k in d :
print(k , d[k])
这很简单。请参阅下面的代码
dictionary = {}
with open("text.txt", "r") as file:
for lines in file:
line = lines.split()
dictionary[line[0]] = line[1:]
print(dictionary)
你可以这样试试
input.txt
writer.py
output.txt
什么是
b
和d
?我已经回答了,请检查。我已经把数据放进了一本字典,还创建了一个字符串文本,正如你所提到的(它实际上不是一个dict
),谢谢。但是这打印的值用逗号分隔,这不是我想要的输出,谢谢。这很简单。我正在努力将值转换为列表。所以list(map)就是这样做的。
dream 4.345 0.456 6.3456
play 0.1223 -0.345 5.3543
faster 1.324 2.435 -2.2345
output_text = '' # Text
d = {} # Dictionary
with open("input.txt") as f:
lines = f.readlines()
for line in lines:
line = line.strip()
arr = line.split()
name = arr[0]
arr = arr[1:]
d[name] = arr
output_text += name + ": [" + ' '.join(arr) + "]\n"
output_text = output_text.strip() # To remove extra new line appended at the end of last line
print(d)
# {'play': ['0.1223', '-0.345', '5.3543'], 'dream': ['4.345', '0.456', '6.3456'], 'faster': ['1.324', '2.435', '-2.2345']}
print(output_text)
# dream: [4.345 0.456 6.3456]
# play: [0.1223 -0.345 5.3543]
# faster: [1.324 2.435 -2.2345]
with open("output.txt", "w") as f:
f.write(output_text)
dream: [4.345 0.456 6.3456]
play: [0.1223 -0.345 5.3543]
faster: [1.324 2.435 -2.2345]