- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
当我在此处输入不在记录列表中的播放器名称时,出现键盘错误异常。我可以搜索它并取回任何有效名称,但如果我输入任何其他内容,我会收到键盘错误。我不太确定如何处理这个问题,因为它已经在处理通过解析我的文件创建的 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 - 其他任何东西都会出现键盘错误,这就是我需要处理的,因此它不会引发错误,而只是打印类似“没有该冠军可用的记录”之类的内容(并打印只有一次,而不是 8 次)
感谢您的帮助!
[edit] 我终于能够在帖子中更新此代码(感谢 martineau 将其添加进来,由于某些原因反引号无法阻止代码并且它显示为粗体普通文本当我粘贴时。无论如何,看看 if not search
,即使根本没有输入任何内容,我怎样才能打印它?只需在 raw_input 上按 return,目前它会打印 * 之后的所有记录***
即使我没有给它任何搜索冠军
最佳答案
您的确切错误发生在哪里?
我只是假设它是 champ = raw_input() #get champion name
然后是 info[champ]
您可以先检查 key 是否存在
if champ not in info:
print 'no records avaialble'
或使用get
if info.get(champ)
或者您可以尝试访问 key
try:
info[champ]
# do stuff
except KeyError:
print 'no records available'
你的问题越具体越好,尽管你解释了你的问题,但你确实没有包含任何细节请始终包含回溯(如果可用),并将相关代码发布在你的帖子中而不是链接上。
关于python - 需要处理keyerror异常python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13606426/
对于我的家庭作业,如果用户输入的键(文本)包含任何非字母字符并重新提示,我被告知要引发一个键错误。到目前为止,我有这个似乎有效但显然没有使用预期的 try/except 结构 key=input("P
编写try/except语句时,是否使用 except KeyError: 或 except KeyError as e: 我得到了相同的结果。 两者有什么区别? KeyError as e 只是更具
我在使用 Python Flask 和 Flask-Mail 库时遇到问题。 我收到一个错误: KeyError: 'mail' 谁能帮我解决这个问题? 我的代码是: # -*- coding: ut
我正在尝试获取 Twitter 登录页面中的隐藏元素。我遵循的过程只是获取该页面中的隐藏元素。但问题是,当我尝试获取这些元素的值时,我遇到了关键错误。代码是: import requests,
我正在尝试将 atexit 处理程序添加到我的代码中。但我发现如果我导入了线程模块,它会给我一个 KeyError 异常。这是 python 线程模块中的错误吗? #!/usr/bin/python2
我正在从 Python2.7 numba 代码转换为 Python3.4。此函数pairwise_distance 将多维数组X 和Y 转换为距离矩阵。 但是,我使用 numba 装饰器 @jit 来
我有 2 个用于生产和开发的独立设置文件以及一个通用的 base.py 设置文件 base.py SECRET_KEY = r"!@#$%^&123456" prod.py from .base im
下面的代码 for k in list(g_score.keys()): print(g_score[k]) 返回 KeyError对我来说: Traceback (most recent c
我收到了一份。在Spyder中第二次从子文件夹导入库时出错,但第一次(重新启动Spyder后)或在Spyder外导入时工作正常。。代码是:。其中,test_lib.py只是。输出结果为:。当库不在子文
我希望以下列方式获取一个对象: Collection.objects.get(name='name', type='library', owner=owner, parent=parent) 不幸的是
如何加入这两个文本文档? 文档 1: 1000001 10:0.471669 250:0.127552 30:0.218773 64:0.249413 1000002 130:0.0839656 10
这段代码有什么问题? 这是我的 HTML: File: 这是我的 Python 脚本: #! /usr/bin/env python import os, sys; from mod_py
我正在尝试在 Linux 中使用 cron 运行一个 Python 脚本,它应该构建一个数据字典。我正在尝试使用 datetime().now().time() 作为字典中的键,但它似乎会引发错误。
我正在尝试更改列或处理列,但出现一些 keyError 错误。从事芝加哥犯罪数据分析工作。 例如当我尝试运行时 ds["DATE OF OCCURRENCE"] = pd.to_datetime([d
我有一个包含以下列的数据框,我只是想通过转换现有列来添加新列。我不明白为什么我会收到此错误,特别是考虑到数据框很好并且我可以在 Zip 上使用 groupby 而不会出现任何索引问题。 print(d
我正在尝试使用 ffmpeg 从视频文件中获取分辨率高度和音频比特率,但出现以下错误,但并不能告诉我太多信息: File "/home/user/code/python/reduce_video_si
我正在为每个单独的州分配区域。我的代码从一个 excel 文件中读取,大约有 30k 行。我建立了一个字典,将每个州分配给一个地区,并为每个州名称分配州缩写。我正在尝试创建一个列来填充每个行项目的区域
我仍在努力学习 Python 词典的来龙去脉。当我运行这个: #!/usr/bin/env python3 d = {} d['foo']['bar'] = 1 我收到 KeyError: 'foo'
我正在尝试使用 Tensorflow 训练线性回归器。 如果我通过自动确定实值列来实例化学习器,则拟合工作正常。 auto_feature_columns = tf.contrib.learn
我正在尝试编写一个可以从YouTube下载整个播放列表的代码。它适用于某些播放列表,但不适用于少数播放列表。我在下面的代码中显示的播放列表之一。也可以随时在此代码上添加更多功能。 如果已有下载该播放列
我是一名优秀的程序员,十分优秀!