首页 > 解决方案 > Cloud Natural Language API Python 脚本错误(客户端对象没有属性 create_rows)

问题描述

我试图创建一个脚本,通过自然语言 API 的分类工具来提供文章,我找到了一个可以做到这一点的教程。我按照这个简单的教程来介绍 Google Cloud 和 Natural Language API。

最终结果应该是一个脚本,它将一堆新文章从 Google Cloud Storage 发送到 Natural Language API 以对文章进行分类,然后将整个内容保存到在 BigQuery 中创建的表中。

我很好地遵循了这个例子,但是在运行最终脚本时,我得到了以下错误:

Traceback (most recent call last):
  File "classify-text.py", line 39, in <module>
    errors = bq_client.create_rows(table, rows_for_bq)
AttributeError: 'Client' object has no attribute 'create_rows'

完整的脚本是:

from google.cloud import storage, language, bigquery

# Set up our GCS, NL, and BigQuery clients
storage_client = storage.Client()
nl_client = language.LanguageServiceClient()
# TODO: replace YOUR_PROJECT with your project name below
bq_client = bigquery.Client(project='Your_Project')

dataset_ref = bq_client.dataset('news_classification')
dataset = bigquery.Dataset(dataset_ref)
table_ref = dataset.table('article_data')
table = bq_client.get_table(table_ref)

# Send article text to the NL API's classifyText method
def classify_text(article):
        response = nl_client.classify_text(
                document=language.types.Document(
                        content=article,
                        type=language.enums.Document.Type.PLAIN_TEXT
                )
        )
        return response


rows_for_bq = []
files = storage_client.bucket('text-classification-codelab').list_blobs()
print("Got article files from GCS, sending them to the NL API (this will take ~2 minutes)...")

# Send files to the NL API and save the result to send to BigQuery
for file in files:
        if file.name.endswith('txt'):
                article_text = file.download_as_string()
                nl_response = classify_text(article_text)
                if len(nl_response.categories) > 0:
                        rows_for_bq.append((article_text, nl_response.categories[0].name, nl_response.categories[0].confidence))

print("Writing NL API article data to BigQuery...")
# Write article text + category data to BQ
errors = bq_client.create_rows(table, rows_for_bq)
assert errors == []

标签: pythongoogle-cloud-platform

解决方案


您正在使用不推荐使用的方法;这些方法在 0.29 版中被标记为过时,并在 1.0.0 版中被完全删除。

你应该client.insert_rows()改用;该方法接受相同的参数

errors = bq_client.insert_rows(table, rows_for_bq)

推荐阅读