Python 除了特定的键错误
Python Except Specific Key Error
我正在使用 Beautiful Soup 解析 XML 文件。有时我的条目缺少一个或多个我正在解析的键。我想设置异常来处理这个。我的代码看起来像这样:
for entry in soup.findAll('entry_name'):
try:
entry_dict = dict(entry.attrs)
x = entry_dict["x"]
y = entry_dict["y"]
z = entry_dict["z"]
d[x] = [y, z]
except KeyError:
y = "0"
d[x] = [y, z]
问题是我可能会缺少 "y"、"z" 或两者 "y and z",具体取决于条目。有没有办法处理特定的 KeyErrors?像这样:
except KeyError "y":
except KeyError "z":
except KeyError "y","z":
您可以检查异常参数:
a = {}
try:
a['a']
except KeyError as e:
# handle key errors you want
if e.args[0] == 'a':
pass
# reraise the exception if not handled
else:
raise
就个人而言,我不会在这里使用 try/except,而是采用检测方法而不是处理方法。
if not 'y' in entry_dict.keys() and not 'z' in entry_dict.keys():
# handle y and z missing
elif not 'y' in entry_dict.keys():
# handle missing y
elif not 'z' in entry_dict.keys():
# handle missing z
答案略有不同:
a = {}
try:
a['a']
except KeyError as e:
# 2 other ways to check what the missing key was
if 'a' in e.args:
pass
if 'a' in e:
pass
# reraise the exception if not handled
else:
raise
我正在使用 Beautiful Soup 解析 XML 文件。有时我的条目缺少一个或多个我正在解析的键。我想设置异常来处理这个。我的代码看起来像这样:
for entry in soup.findAll('entry_name'):
try:
entry_dict = dict(entry.attrs)
x = entry_dict["x"]
y = entry_dict["y"]
z = entry_dict["z"]
d[x] = [y, z]
except KeyError:
y = "0"
d[x] = [y, z]
问题是我可能会缺少 "y"、"z" 或两者 "y and z",具体取决于条目。有没有办法处理特定的 KeyErrors?像这样:
except KeyError "y":
except KeyError "z":
except KeyError "y","z":
您可以检查异常参数:
a = {}
try:
a['a']
except KeyError as e:
# handle key errors you want
if e.args[0] == 'a':
pass
# reraise the exception if not handled
else:
raise
就个人而言,我不会在这里使用 try/except,而是采用检测方法而不是处理方法。
if not 'y' in entry_dict.keys() and not 'z' in entry_dict.keys():
# handle y and z missing
elif not 'y' in entry_dict.keys():
# handle missing y
elif not 'z' in entry_dict.keys():
# handle missing z
a = {}
try:
a['a']
except KeyError as e:
# 2 other ways to check what the missing key was
if 'a' in e.args:
pass
if 'a' in e:
pass
# reraise the exception if not handled
else:
raise