for 循环中的错误/异常处理 - python
Error/ Exception handling in for loop - python
我正在使用 Google Cloud NL API 来分析一些描述的情绪。至于某些行,错误 InvalidArgument: 400 The language vi is not supported for document_sentiment analysis.
不断弹出,我想围绕它构建一种方法,而不是拼命地试图找到发生这种情况的原因并删除负责的行。不幸的是,我是 Python 的新手,不确定如何正确操作。
我的代码如下:
description_list = []
sentimentscore_list=[]
magnitude_list=[]
# Create a Language client
language_client = google.cloud.language.LanguageServiceClient()
for i in range(len(description)): # use the translated description if the original description is not in English
if description_trans[i] == '':
descr = description[i]
else:
descr = description_trans[i]
document = google.cloud.language.types.Document(
content=descr,
type=google.cloud.language.enums.Document.Type.PLAIN_TEXT)
# Use Language to detect the sentiment of the text.
response = language_client.analyze_sentiment(document=document)
sentiment = response.document_sentiment
sentimentscore_list.append(sentiment.score)
magnitude_list.append(sentiment.magnitude)
# Add the description that was actually used to the description list
description_list.append(descr)
谁能向我解释如何将这个 for 循环(或者可能后一部分就足够了)包装到 error/exception 处理中,以便它只是 "skips over" 它不能阅读并继续下一篇?此外,我希望仅在实际分析描述时才附加 'description_list'(而不是在它卡在错误处理中时)。
非常感谢任何帮助!!谢谢:)
编辑:有人要求我提供更完整的错误回溯:
回溯(最近调用最后):
File "<ipython-input-64-6e3db1d976c9>", line 1, in <module>
runfile('/Users/repos/NLPAnalysis/GoogleTest.py', wdir='/Users/repos/NLPAnalysis')
File "/Users/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 710, in runfile
execfile(filename, namespace)
File "/Users/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/repos/NLPAnalysis/GoogleTest.py", line 45, in <module>
response = language_client.analyze_sentiment(document=document)
File "/Users/anaconda3/lib/python3.6/site-packages/google/cloud/language_v1/gapic/language_service_client.py", line 180, in analyze_sentiment
return self._analyze_sentiment(request, retry=retry, timeout=timeout)
File "/Users/anaconda3/lib/python3.6/site-packages/google/api_core/gapic_v1/method.py", line 139, in __call__
return wrapped_func(*args, **kwargs)
File "/Users/anaconda3/lib/python3.6/site-packages/google/api_core/retry.py", line 260, in retry_wrapped_func
on_error=on_error,
File "/Users/anaconda3/lib/python3.6/site-packages/google/api_core/retry.py", line 177, in retry_target
return target()
File "/Users/anaconda3/lib/python3.6/site-packages/google/api_core/timeout.py", line 206, in func_with_timeout
return func(*args, **kwargs)
File "/Users/anaconda3/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 56, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
InvalidArgument: 400 The language vi is not supported for document_sentiment analysis.
在回溯中,查看第四行,这是您代码中导致异常的同一行。我们总是将 try except 放在我们认为会导致异常的代码块周围。其他所有东西都放在块外面。
try:
response = language_client.analyze_sentiment(document=document)
except InvalidArgument:
continue
# Assuming none of these would work if we don't get response?
description_list.append(descr)
sentiment = response.document_sentiment
entimentscore_list.append(sentiment.score)
magnitude_list.append(sentiment.magnitude)
# Add the description that was actually used to the description list
我们尝试从语言客户端获得响应,它引发了一个异常说InvalidArgument,我们抓住了。现在我们知道我们不需要做任何事情,我们使用 continue,然后继续下一次迭代。
您可能需要像 -
一样导入 InvalidArgument
from google.api_core.exceptions import InvalidArgument
在代码中使用它之前。
关于继续,你是对的。更多关于 continue statement and how to handle exceptions in python.
我同意 ThatBird 的观点,即在 try 块中包装太多代码会使调试内部错误变得复杂。我建议使用 python 的 continue 关键字。
try:
# smallest block of code you foresee an error in
response = language_client.analyze_sentiment(document=document) # I think your exception is being raised in this call
except InvalidArgument as e:
# your trace shows InvalidArgument being raised and it appears you dont care about it
continue # continue to next iteration since this error is expected
except SomeOtherOkayException as e:
# this is an example exception that is also OK and "skippable"
continue # continue to next iteration
except Exception as e:
# all other exceptions are BAD and unexpected.This is a larger problem than just this loop
raise e # break the looping and raise to calling function
sentiment = response.document_sentiment
sentimentscore_list.append(sentiment.score)
magnitude_list.append(sentiment.magnitude)
# Add the description that was actually used to the description list
description_list.append(descr)
# more code here...
本质上,您是在明确捕获预期的异常,并在出现异常时丢弃该迭代并继续下一个迭代。您应该提出所有其他意外情况。
我正在使用 Google Cloud NL API 来分析一些描述的情绪。至于某些行,错误 InvalidArgument: 400 The language vi is not supported for document_sentiment analysis.
不断弹出,我想围绕它构建一种方法,而不是拼命地试图找到发生这种情况的原因并删除负责的行。不幸的是,我是 Python 的新手,不确定如何正确操作。
我的代码如下:
description_list = []
sentimentscore_list=[]
magnitude_list=[]
# Create a Language client
language_client = google.cloud.language.LanguageServiceClient()
for i in range(len(description)): # use the translated description if the original description is not in English
if description_trans[i] == '':
descr = description[i]
else:
descr = description_trans[i]
document = google.cloud.language.types.Document(
content=descr,
type=google.cloud.language.enums.Document.Type.PLAIN_TEXT)
# Use Language to detect the sentiment of the text.
response = language_client.analyze_sentiment(document=document)
sentiment = response.document_sentiment
sentimentscore_list.append(sentiment.score)
magnitude_list.append(sentiment.magnitude)
# Add the description that was actually used to the description list
description_list.append(descr)
谁能向我解释如何将这个 for 循环(或者可能后一部分就足够了)包装到 error/exception 处理中,以便它只是 "skips over" 它不能阅读并继续下一篇?此外,我希望仅在实际分析描述时才附加 'description_list'(而不是在它卡在错误处理中时)。
非常感谢任何帮助!!谢谢:)
编辑:有人要求我提供更完整的错误回溯:
回溯(最近调用最后):
File "<ipython-input-64-6e3db1d976c9>", line 1, in <module>
runfile('/Users/repos/NLPAnalysis/GoogleTest.py', wdir='/Users/repos/NLPAnalysis')
File "/Users/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 710, in runfile
execfile(filename, namespace)
File "/Users/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/repos/NLPAnalysis/GoogleTest.py", line 45, in <module>
response = language_client.analyze_sentiment(document=document)
File "/Users/anaconda3/lib/python3.6/site-packages/google/cloud/language_v1/gapic/language_service_client.py", line 180, in analyze_sentiment
return self._analyze_sentiment(request, retry=retry, timeout=timeout)
File "/Users/anaconda3/lib/python3.6/site-packages/google/api_core/gapic_v1/method.py", line 139, in __call__
return wrapped_func(*args, **kwargs)
File "/Users/anaconda3/lib/python3.6/site-packages/google/api_core/retry.py", line 260, in retry_wrapped_func
on_error=on_error,
File "/Users/anaconda3/lib/python3.6/site-packages/google/api_core/retry.py", line 177, in retry_target
return target()
File "/Users/anaconda3/lib/python3.6/site-packages/google/api_core/timeout.py", line 206, in func_with_timeout
return func(*args, **kwargs)
File "/Users/anaconda3/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 56, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
InvalidArgument: 400 The language vi is not supported for document_sentiment analysis.
在回溯中,查看第四行,这是您代码中导致异常的同一行。我们总是将 try except 放在我们认为会导致异常的代码块周围。其他所有东西都放在块外面。
try:
response = language_client.analyze_sentiment(document=document)
except InvalidArgument:
continue
# Assuming none of these would work if we don't get response?
description_list.append(descr)
sentiment = response.document_sentiment
entimentscore_list.append(sentiment.score)
magnitude_list.append(sentiment.magnitude)
# Add the description that was actually used to the description list
我们尝试从语言客户端获得响应,它引发了一个异常说InvalidArgument,我们抓住了。现在我们知道我们不需要做任何事情,我们使用 continue,然后继续下一次迭代。
您可能需要像 -
一样导入 InvalidArgumentfrom google.api_core.exceptions import InvalidArgument
在代码中使用它之前。
关于继续,你是对的。更多关于 continue statement and how to handle exceptions in python.
我同意 ThatBird 的观点,即在 try 块中包装太多代码会使调试内部错误变得复杂。我建议使用 python 的 continue 关键字。
try:
# smallest block of code you foresee an error in
response = language_client.analyze_sentiment(document=document) # I think your exception is being raised in this call
except InvalidArgument as e:
# your trace shows InvalidArgument being raised and it appears you dont care about it
continue # continue to next iteration since this error is expected
except SomeOtherOkayException as e:
# this is an example exception that is also OK and "skippable"
continue # continue to next iteration
except Exception as e:
# all other exceptions are BAD and unexpected.This is a larger problem than just this loop
raise e # break the looping and raise to calling function
sentiment = response.document_sentiment
sentimentscore_list.append(sentiment.score)
magnitude_list.append(sentiment.magnitude)
# Add the description that was actually used to the description list
description_list.append(descr)
# more code here...
本质上,您是在明确捕获预期的异常,并在出现异常时丢弃该迭代并继续下一个迭代。您应该提出所有其他意外情况。