簡體   English   中英

Python - 使 IBM Natural Language Understanding API 分析 csv 文件的每一行

[英]Python - Making IBM Natural Language Understanding API analyze each row of a csv file

我正在使用 IBM Watson Natural Language Understanding 的 API 來執行一些情感分析。 我遵循了文檔,並且能夠分析我在代碼中輸入的 url 或一些文本。

但是,我不想分析一些文本,而是希望 IBM NLU 分析 csv 文件。 每行是一個不同的文本,應該被分析,output 應該是相同的 csv 文件,在相關文本旁邊的另一列中具有情感和情感分析的值。

我想這可以通過 json 和一些 Python 循環來完成,但它確實超出了我在 Python 中的新技能。

目前,我有以下代碼:

import json
from ibm_watson import NaturalLanguageUnderstandingV1 
from ibm_watson.natural_language_understanding_v1 import Features, EmotionOptions, SentimentOptions
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator


authenticator = IAMAuthenticator('XXX')
natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2019-07-12',
    authenticator=authenticator
)

natural_language_understanding.set_service_url('https://gateway-lon.watsonplatform.net/natural-language-understanding/api')

response = natural_language_understanding.analyze(
    text="Bruce Banner is the Hulk and Bruce Wayne is BATMAN! Superman fears not Banner, but Wayne.",
    features=Features(emotion=EmotionOptions(),
                      sentiment=SentimentOptions())).get_result()

print(json.dumps(response, indent=2))

預先感謝您的幫助,N。

你問了很多基本的 Python 問題(回答 Python Cookbook 的禮貌):

1:如何從a.csv文件中讀取數據

import csv 

with open('abc.csv') as f:
  csvFile = csv.reader(f)
  headers = next(csvFile)
  for r in csvFile:
    # Process row 
    # Data in column 1 is r[0], column 2 is r[1] etc.
    # eg. analyseTheData(r[0])

2:如何將分析響應與輸入結合起來

rows = []
for r in csfFile:
  d = analyseTheData(r[0])
  row = [r]
  row.extend(d)
  rows.append(row)

3:如何在標題中添加額外的列

headers.extend(['aaa', 'bbb', 'ccc'])

4:如何將數據寫入a.csv文件

import csv

with open('xyz.csf') as f:
  csvFile = csv.writer(f)
  csfFile.writerow(headers)
  csvFile.writerows(rows)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM