Python 即使最后一个命令(但不是第一个命令)引发异常,Try块也会给出输出
我使用try/except逐行读取文件时捕捉问题。try块包含一系列操作,最后一个操作通常是异常的原因。令人惊讶的是,我注意到所有以前的操作都是在try块中执行的,即使在引发异常时也是如此。当试图将我创建的字典转换为数据帧时,这是一个问题,因为列表的长度不相等 此代码会产生以下问题:Python 即使最后一个命令(但不是第一个命令)引发异常,Try块也会给出输出,python,python-3.x,try-except,Python,Python 3.x,Try Except,我使用try/except逐行读取文件时捕捉问题。try块包含一系列操作,最后一个操作通常是异常的原因。令人惊讶的是,我注意到所有以前的操作都是在try块中执行的,即使在引发异常时也是如此。当试图将我创建的字典转换为数据帧时,这是一个问题,因为列表的长度不相等 此代码会产生以下问题: d = {'dates':[],'states':[], 'longitude':[], 'latitude':[], 'tweet_ids':[], 'user_ids':[], 'source':[]} for
d = {'dates':[],'states':[], 'longitude':[], 'latitude':[], 'tweet_ids':[], 'user_ids':[], 'source':[]}
for file in f:
print("Processing file "+file)
t1 = file.split('/')[-1].split("_")
date = t1[0]
state_code = t1[1]
state = list(states_ref.loc[states_ref.code==state_code]['abbr'])[0]
collection = JsonCollection(file)
counter = 0
for tweet in collection.get_iterator():
counter += 1
try:
d['dates'].append(date)
d['states'].append(state)
t2 = tweet_parser.get_entity_field('geo', tweet)
if t2 == None:
d['longitude'].append(t2)
d['latitude'].append(t2)
else:
d['longitude'].append(t2['coordinates'][1])
d['latitude'].append(t2['coordinates'][0])
#note: the 3 lines bellow are the ones that can raise an exception
temp = tweet_parser.get_entity_field('source', tweet)
t5 = re.findall(r'>(.*?)<', temp)[0]
d['source'].append(t5)
except:
c += 1
print("Tweet {} in file {} had a problem and got skipped".format(counter, file))
print("This is a total of {} tweets I am missing from the {} archive I process.".format(c, sys.argv[1]))
next
tab = pd.DataFrame.from_dict(d)
我已经通过移动易于在顶部给出错误的操作修复了这个问题,但是我想更好地理解为什么try/except的行为是这样的。有什么想法吗
此代码适用于:
d = {'dates':[],'states':[], 'longitude':[], 'latitude':[], 'tweet_ids':[], 'user_ids':[], 'source':[]}
for file in f:
print("Processing file "+file)
t1 = file.split('/')[-1].split("_")
date = t1[0]
state_code = t1[1]
state = list(states_ref.loc[states_ref.code==state_code]['abbr'])[0]
collection = JsonCollection(file)
counter = 0
for tweet in collection.get_iterator():
counter += 1
try:
#note: the 3 lines bellow are the ones that can raise an exception
temp = tweet_parser.get_entity_field('source', tweet)
t5 = re.findall(r'>(.*?)<', temp)[0]
d['source'].append(t5)
d['dates'].append(date)
d['states'].append(state)
t2 = tweet_parser.get_entity_field('geo', tweet)
if t2 == None:
d['longitude'].append(t2)
d['latitude'].append(t2)
else:
d['longitude'].append(t2['coordinates'][1])
d['latitude'].append(t2['coordinates'][0])
except:
c += 1
print("Tweet {} in file {} had a problem and got skipped".format(counter, file))
print("This is a total of {} tweets I am missing from the {} archive I process.".format(c, sys.argv[1]))
next
tab = pd.DataFrame.from_dict(d)
在附加到目标对象之前,始终可以使用时态对象来保存函数的输出。这样,如果出现故障,它将在将数据放入目标对象之前引发异常
try:
#Put all data into a temporal Dictionary
#Can raise an exception here
temp = tweet_parser.get_entity_field('source', tweet)
t2 = tweet_parser.get_entity_field('geo', tweet)
tempDictionary = {
"source" : re.findall(r'>(.*?)<', temp)[0],
"latitude" : None if (t2 is None) else t2['coordinates'][1],
"longitude" : None if (t2 is None) else t2['coordinates'][0]
}
#Append data from temporal Dictionary
d['source'].append(tempDictionary['source'])
d['latitude'].append(tempDictionary['latitude'])
d['longitude'].append(tempDictionary['longitude'])
d['dates'].append(date)
d['states'].append(state)
except:
c += 1
print("Tweet {} in file {} had a problem and got skipped".format(counter, file))
print("This is a total of {} tweets I am missing from the {} archive I process.".format(c, sys.argv[1]))
您是说,如果抛出异常,您希望以前运行的语句的效果会反转吗?try/except块与数据库事务不同。如果一个操作成功了,它就成功了——没有回滚。啊!谢谢那么,在尝试任何一个步骤时,引发异常的最佳方法是什么?每个模块都有一个单独的try/except块?有什么更优雅的方法可以做到这一点吗?@Rodonikiatanasiadou-Only将抛出的代码理想情况下应该在块中,并且,您确实应该指定要捕获的确切异常。盲目捕捉所有异常几乎总是一个非常糟糕的主意。谢谢@Carcigenicate。我这样做的原因是,我的文件中的某些行的行为出人意料,而且我有大量的数据,所以我不介意扔掉一把,尽管没有对错误进行深入的故障排除,但我会密切关注数据量。