[英]how to convert text file to dictionary in python
我需要将不同长度的行转换为一本字典。 这是针对球员的数据。 文本文件的格式如下。 我需要返回一本包含每个玩家数据的字典。
{Lebron James:(25,7,1),(34,5,6), Stephen Curry: (25,7,1),(34,5,6), Draymond Green: (25,7,1),(34,5,6)}
数据:
Lebron James
25,7,1
34,5,6
Stephen Curry
25,7,1
34,5,6
Draymond Green
25,7,1
34,5,6
我需要启动代码的帮助。 到目前为止,我有一个删除空白行并使这些行成为列表的代码。
myfile = open("stats.txt","r")
for line in myfile.readlines():
if line.rstrip():
line = line.replace(",","")
line = line.split()
我认为这应该做您想要的:
data = {}
with open("myfile.txt","r") as f:
for line in f:
# Skip empty lines
line = line.rstrip()
if len(line) == 0: continue
toks = line.split(",")
if len(toks) == 1:
# New player, assumed to have no commas in name
player = toks[0]
data[player] = []
elif len(toks) == 3:
data[player].append(tuple([int(tok) for tok in toks]))
else: raise ValueErorr # or something
格式有些模棱两可,因此我们必须对名称可以做些假设。 我假设名称不能在此处包含逗号,但是如果需要,可以尝试解析int,int,int,然后放慢一点,如果解析失败,则将其视为名称,可以放宽一点。
这是执行此操作的一种简单方法:
scores = {}
with open('stats.txt', 'r') as infile:
i = 0
for line in infile.readlines():
if line.rstrip():
if i%3!=0:
t = tuple(int(n) for n in line.split(","))
j = j+1
if j==1:
score1 = t # save for the next step
if j==2:
score = (score1,t) # finalize tuple
scores.update({name:score}) # add to dictionary
else:
name = line[0:-1] # trim \n and save the key
j = 0 # start over
i=i+1 #increase counter
print scores
也许是这样的:
对于Python 2.x
myfile = open("stats.txt","r")
lines = filter(None, (line.rstrip() for line in myfile))
dictionary = dict(zip(lines[0::3], zip(lines[1::3], lines[2::3])))
对于Python 3.x
myfile = open("stats.txt","r")
lines = list(filter(None, (line.rstrip() for line in myfile)))
dictionary = dict(zip(lines[0::3], zip(lines[1::3], lines[2::3])))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.