我正在尝试读取文件并将内容放入列表中。我之前已经完成了这个时间并且它已经工作但是这次它会抛出错误“列表索引超出范围”。
代码是:
with open("File.txt") as f:
scores = []
for line in f:
fields = line.split()
scores.append( (fields[0], fields[1]))
print(scores)
文本文件采用格式;
Alpha:[0, 1]
Bravo:[0, 0]
Charlie:[60, 8, 901]
Foxtrot:[0]
我不明白为什么它会给我这个问题。是因为每件商品都有多个价值吗?或者我的文本文件中有冒号这个事实?
如何解决这个问题?
由于
答案 0 :(得分:0)
如果我理解你,这段代码会打印出你想要的结果:
import re
with open("File.txt") as f:
# Let's make dictionary for scores {name:scores}.
scores = {}
# Define regular expressin to parse team name and team scores from line.
patternScore = '\[([^\]]+)\]'
patternName = '(.*):'
for line in f:
# Find value for team name and its scores.
fields = re.search(patternScore, line).groups()[0].split(', ')
name = re.search(patternName, line).groups()[0]
# Update dictionary with new value.
scores[name] = fields
# Print output first goes first element of keyValue in dict then goes keyName
for key in scores:
print (scores[key][0] + ':' + key)
您将收到以下输出:
60:Charlie
0:Alpha
0:Bravo
0:Foxtrot