如何在python中将文本文件转换为字典
我需要将不同长度的行转换为一个字典。这是关于球员统计的。文本文件的格式如下所示。我需要返回每个玩家的统计数据字典如何在python中将文本文件转换为字典,python,list,file,dictionary,text,Python,List,File,Dictionary,Text,我需要将不同长度的行转换为一个字典。这是关于球员统计的。文本文件的格式如下所示。我需要返回每个玩家的统计数据字典 {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 3
{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,如果解析失败,您可以将其作为名称处理。我认为这应该满足您的要求:
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
下面是一个简单的方法:
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
也许是这样的: 对于Python2.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])))
对于Python3.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])))
也许是这样的: 对于Python2.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])))
对于Python3.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])))
文本文件是否需要采用这种格式,或者是可以更改的格式?这种格式不容易解析。你用空字符串替换逗号的方法在这里行不通。当然,这些行会被转换为列表,但你也会删除玩家统计中的逗号。是的,文本文件必须采用该格式@Michaelpratt是该格式的文本文件,还是可以更改?这种格式不容易解析。你用空字符串替换逗号的方法在这里行不通。当然,这些行会被转换成一个列表,但你也会删除玩家统计中的逗号。是的,文本文件必须采用@MichaelPratt的格式。你是说新玩家:
,如果len(toks)==1
str.split
将永远不会有长度为0的输出,即使空字符串'
也将作为带有一个索引的列表返回(因此输出长度为1)。@M.T抱歉,修复了。你是说新玩家:如果len(toks)==1
str.split
将永远不会有长度为0的输出,即使空字符串'
也将作为一个带有一个索引的列表返回(因此输出的长度为1)。@M.T抱歉,已修复。