1

当我在此处输入不在记录列表中的玩家姓名时,我收到了 keyerror 异常。我可以搜索它并取回任何有效的名称,但如果我输入其他任何内容,我会收到一个 keyerror。我不太确定如何处理这个问题,因为已经在处理解析我的文件创建的 3 组数据时有点令人困惑。

我知道这段代码很糟糕,我是 python 新手,所以请原谅混乱 - 另请注意,这是一个让此功能正常工作的测试文件,然后我将其写入我真正的主文件中的函数。有点像这里的测试平台,如果这有任何意义的话。

这是我的数据文件stats4.txt中的内容:

[00000] Cho'Gath - 12/16/3 - Loss - 2012-11-22
[00001] Fizz - 12/5/16 - Win - 2012-11-22
[00002] Caitlyn - 13/4/6 - Win - 2012-11-22
[00003] Sona - 4/5/9 - Loss - 2012-11-23
[00004] Sona - 2/1/20 - Win - 2012-11-23
[00005] Sona - 6/3/17 - Loss - 2012-11-23
[00006] Caitlyn - 14/2/16 - Win - 2012-11-24
[00007] Lux - 10/2/14 - Win - 2012-11-24
[00008] Sona - 8/1/22 - Win - 2012-11-27

这是我的代码:

import re

info = {}
records = []
search = []
with open('stats4.txt') as data:
    for line in data:
        gameid = [item.strip('[') for item in line.split(']')]
        del gameid[-1]
        gameidstr = ''.join(gameid)
        gameid = gameidstr
        line = line[7:]
        player, stats, outcome, date = [item.strip() for item in line.split('-', 3)]
        stats = dict(zip(('kills', 'deaths', 'assists'), map(int, stats.split('/'))))
        date = tuple(map(int, date.split('-')))
        info[player] = dict(zip(('gameid', 'player', 'stats', 'outcome', 'date'), (gameid, player, stats, outcome, date)))
        records.append(tuple((gameid, info[player])))

print "\n\n", info, "\n\n" #print the info dictionary just to see 
champ = raw_input() #get champion name
#print info[champ].get('stats').get('kills'), "\n\n"
#print "[%s] %s - %s/%s/%s - %s-%s-%s" % (info[champ].get('gameid'), champ, info[champ].get('stats').get('kills'), info[champ].get('stats').get('deaths'), info[champ].get('stats').get('assists'), info[champ].get('date')[0], info[champ].get('date')[1], info[champ].get('date')[2])
#print "\n\n"
#print info[champ].values()

i = 0
for item in records: #this prints out all records
    print "\n", "[%s] %s - %s/%s/%s - %s - %s-%s-%s" % (records[i][0], records[i][1]['player'], records[i][1]['stats']['kills'], records[i][1]['stats']['deaths'], records[i][1]['stats']['assists'], records[i][1]['outcome'], records[i][1]['date'][0], records[i][1]['date'][1], records[i][1]['date'][2])
    i = i + 1

print "\n" + "*" * 50
i = 0
for item in records:
    if champ in records[i][1]['player']:
        search.append(records[i][1])
    else:
        pass
    i = i + 1

s = 0

if not search:
    print "no availble records" #how can I get this to print even if nothing is inputted in raw_input above for champ?


print "****"
for item in search:
        print "\n[%s] %s - %s/%s/%s - %s - %s-%s-%s" % (search[s]['gameid'], search[s]['player'], search[s]['stats']['kills'], search[s]['stats']['deaths'], search[s]['stats']['assists'], search[s]['outcome'], search[s]['date'][0], search[s]['date'][1], search[s]['date'][2])
        s = s + 1

我尝试设置一个 Try;除了某种东西,但在输入无效的玩家名称时我无法得到任何不同的结果。我想我可能可以用一个函数设置一些东西,如果名称存在或不存在,则返回不同的东西,但我想我只是让自己有点困惑。另请注意,对于不匹配的 8 条记录,确实不会打印任何匹配项,尽管这并不是我想要的工作方式。基本上我需要为任何无效的输入名称获取类似的东西,而不仅仅是一个恰好不在循环中的记录中的有效输入。

此数据的有效输入名称是:Cho'Gath、Fizz、Caitlyn、Sona 或 Lux - 其他任何内容都会产生 keyerror,这就是我需要处理的内容,因此它不会引发错误,而只会打印类似“没有记录”的内容可用于那个冠军”(并且只打印一次,而不是 8 次)

谢谢你的帮助!

[编辑] 我终于能够在帖子中更新此代码(感谢 martineau 将其添加,由于某种原因,反引号无法阻止代码,并且当我粘贴时它显示为粗体普通文本。无论如何,看看if not search,即使什么也没输入,我怎么能打印出来?只需在 raw_input 上按返回,目前它会打印所有记录,****即使我没有给它任何搜索冠军

4

2 回答 2

3

您的确切错误发生在哪里?

我只是假设它是什么时候champ = raw_input() #get champion name

接着info[champ]

您可以先检查密钥是否存在

if champ not in info:
  print 'no records avaialble'

或使用get

if info.get(champ)

或者您可以尝试访问密钥

try:
  info[champ] 
  # do stuff
except KeyError:
  print 'no records available'

您的问题越具体越好,尽管您解释了您的问题,但您确实没有包含任何细节。如果可用,请始终包含回溯,并将相关代码发布在您的帖子中,而不是链接上。

于 2012-11-28T13:48:14.897 回答
1

这是我认为可以解决您的问题的一些修改。我还重新格式化了代码以使其更具可读性。在 Python 中,如果上一行有未配对的 '(' 或 '[' ,则可以通过以 a 结尾\或直接转到下一行来将长行继续到下一行。

此外,我在我的问题或答案中输入代码的方式是将其从我的文本编辑器中剪切出来,然后将其粘贴到编辑窗口中,之后我确保它全部被选中,然后只使用{}编辑顶部的工具窗口来格式化它。

import re
from pprint import pprint

info = {}
records = []
with open('stats4.txt') as data:
    for line in data:
        gameid = [item.strip('[') for item in line.split(']')]
        del gameid[-1]
        gameidstr = ''.join(gameid)
        gameid = gameidstr
        line = line[7:]
        player, stats, outcome, date = [item.strip() for item in line.split('-', 3)]
        stats = dict(zip(('kills', 'deaths', 'assists'), map(int, stats.split('/'))))
        date = tuple(map(int, date.split('-')))
        info[player] = dict(zip(('gameid', 'player', 'stats', 'outcome', 'date'),
                                (gameid, player, stats, outcome, date)))
        records.append(tuple((gameid, info[player])))

#print "\n\n", info, "\n\n" #print the info dictionary just to see
pprint(info)
champ = raw_input("Champ's name: ") #get champion name
#print info[champ].get('stats').get('kills'), "\n\n"
#print "[%s] %s - %s/%s/%s - %s-%s-%s" % (
#       info[champ].get('gameid'), champ, info[champ].get('stats').get('kills'),
#       info[champ].get('stats').get('deaths'), info[champ].get('stats').get('assists'),
#       info[champ].get('date')[0], info[champ].get('date')[1],
#       info[champ].get('date')[2])
#print "\n\n"
#print info[champ].values()

i = 0
for item in records: #this prints out all records
    print "\n", "[%s] %s - %s/%s/%s - %s - %s-%s-%s" % (
                 records[i][0], records[i][1]['player'], records[i][1]['stats']['kills'],
                 records[i][1]['stats']['deaths'], records[i][1]['stats']['assists'],
                 records[i][1]['outcome'], records[i][1]['date'][0],
                 records[i][1]['date'][1], records[i][1]['date'][2])
    i = i + 1

print "\n" + "*" * 50
i = 0
search = []
for item in records:
    if champ in records[i][1]['player']:
        search.append(records[i][1])
    i = i + 1
if not search:
    print "no match"
    exit()

s = 0
for item in search:
        print "\n[%s] %s - %s/%s/%s - %s - %s-%s-%s" % (search[s]['gameid'],
              search[s]['player'], search[s]['stats']['kills'],
              search[s]['stats']['deaths'], search[s]['stats']['assists'],
              search[s]['outcome'], search[s]['date'][0], search[s]['date'][1],
              search[s]['date'][2])
        s = s + 1
于 2012-11-28T14:36:21.110 回答