首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >for loop - python中的错误/异常处理

for loop - python中的错误/异常处理
EN

Stack Overflow用户
提问于 2018-07-06 04:32:43
回答 2查看 17.3K关注 0票数 3

我正在使用Google Cloud NL API来分析一些描述的情绪。对于错误InvalidArgument: 400 The language vi is not supported for document_sentiment analysis.不断弹出的一些行,我想构建一种绕过它的方法,而不是拼命地寻找发生这种情况的原因,并删除负责的行。不幸的是,我对Python比较陌生,不确定如何正确地使用它。

我的代码如下:

代码语言:javascript
复制
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循环(或者可能后面的部分就足够了)封装到错误/异常处理中,这样它就可以简单地“跳过”它无法读取的循环,并继续下一个循环?另外,我希望'description_list‘只在描述被实际分析的时候被附加(所以当它被错误处理卡住的时候就不会了)。

任何帮助都非常感谢!谢谢:)

编辑:我被要求提供更完整的错误回溯:

回溯(最近一次调用):

代码语言:javascript
复制
  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.
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-06 06:43:59

我同意ThatBird的观点,在try块中包装太多代码会使调试内部错误变得复杂。我建议使用python的continue关键字。

代码语言:javascript
复制
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...

本质上,您是在显式地捕获预期的异常,并在它们发生时丢弃该迭代并继续到下一次迭代。您应该引发所有其他非预期的异常。

票数 3
EN

Stack Overflow用户

发布于 2018-07-06 04:52:06

在回溯中,看看第四行,它与您的代码中导致异常的代码行相同。我们总是将try放在我们认为会导致异常的代码块周围。其他的都放在区块之外。

代码语言:javascript
复制
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的看法是对的。更多关于continue statementhow to handle exceptions in python的信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51199436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档