AttributeError:“ LanguageServiceClient”对象没有属性“ classify_text”

时间:2018-10-31 22:38:43

标签: python google-cloud-platform google-natural-language

我正在尝试对一些文本进行分类,并具有以下代码:

from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types


def classify_text(text):
    """Classifies content categories of the provided text."""
    client = language.LanguageServiceClient()

    if isinstance(text, six.binary_type):
        text = text.decode('utf-8')

    document = types.Document(
        content=text.encode('utf-8'),
        type=enums.Document.Type.PLAIN_TEXT)

    categories = client.classify_text(document).categories

    for category in categories:
        print(u'=' * 20)
        print(u'{:<16}: {}'.format('name', category.name))
        print(u'{:<16}: {}'.format('confidence', category.confidence))

但是当我打电话给classify_text('Hello')时,我得到了:

AttributeError: 'LanguageServiceClient' object has no attribute 'classify_text'

我似乎在这里找不到关于此错误的任何问题。有人知道这里发生了什么吗?

2 个答案:

答案 0 :(得分:1)

我不赞成使用我使用的版本0.29。当前版本是1.1,正确的功能如下:

def classify(text, verbose=True):
    """Classify the input text into categories. """

    language_client = language.LanguageServiceClient()

    document = language.types.Document(
        content=text,
        type=language.enums.Document.Type.PLAIN_TEXT)
    response = language_client.classify_text(document)
    categories = response.categories

    result = {}

    for category in categories:
        # Turn the categories into a dictionary of the form:
        # {category.name: category.confidence}, so that they can
        # be treated as a sparse vector.
        result[category.name] = category.confidence

    if verbose:
        print(text)
        for category in categories:
            print(u'=' * 20)
            print(u'{:<16}: {}'.format('category', category.name))
            print(u'{:<16}: {}'.format('confidence', category.confidence))

    return result

找到该功能here,但是找到我误用的功能here

答案 1 :(得分:0)

尝试:

categories = client.classify_text(document)
cat = categories.categories

我知道这是基本的调试。

您还可以注释掉文档的声明,然后执行以下操作:

document = {}

并检查是否抛出相同的错误。

由于它应该以{{1​​}}的任何一种方式返回,因此可能会开始将问题分成几部分。在这种情况下,最好一一进攻。