【发布时间】:2021-07-28 14:40:18
【问题描述】:
我将数据放入一个 csv 文件(称为“Essential Data_posts”)。在我的主要内容中,我从这个文件中提取了一个特定的列(称为“帖子文本”),以便我可以使用 Google Cloud NLP 分析帖子文本以进行情感实体分析。然后我将此分析放入另一个 csv 文件(称为“SentimentAnalysis”)中。为此,我将与情感实体分析有关的所有信息放入一个数组中(每条信息一个)。
我遇到的问题是,当我执行我的代码时,SentimentAnalysis 文件中除了标题之外什么都没有显示,例如。 “代表名称”。当我请求所有数组的长度时,我发现每个数组的长度都是0,所以它们没有添加信息。
我使用的是 Ubuntu 21.04 和 Google Cloud Natural Language。我在终端中运行这一切,而不是谷歌云平台。我也在使用 Python3 和 emacs 文本编辑器。
from google.cloud import language_v1
import pandas as pd
import csv
import os
#lists we are appending to
representativeName = []
entity = []
salienceScore = []
entitySentimentScore = []
entitySentimentMagnitude = []
metadataNames = []
metadataValues = []
mentionText = []
mentionType = []
def sentiment_entity(postTexts):
client = language_v1.LanguageServiceClient()
type_ = language_v1.Document.Type.PLAIN_TEXT
language = "en"
document = {"content": post_texts, "type": type_, "language": language}
encodingType = language_v1.EncodingType.UTF8
response = client.analyze_entity_sentiment(request = {'document': document, 'encoding type': encodingType})
#loop through entities returned from the API
for entity in response.entities:
representativeName.append(entity.name)
entity.append(language_v1.Entity.Type(entity.type_).name)
salienceScore.append(entity.salience)
entitySentimentScore.append(sentiment.score)
entitySentimentMagnitude.append(sentiment.magnitude)
#loop over metadata associated with entity
for metadata_name, metadata_value in entity.metadata.items():
metadataNames.append(metadata_name)
metadataValues.append(metadata_value)
#loop over the mentions of this entity in the input document
for mention in entity.mentions:
mentionText.append(mention.text.content)
mentionType.append(mention.type_)
#put the lists into the csv file (using pandas)
data = {
"Representative Name": representativeName,
"Entity": entity,
"Salience Score": salienceScore,
"Entity Sentiment Score": entitySentimentScore,
"Entity Sentiment Magnitude": entitySentimentMagnitude,
"Metadata Name": metadataNames,
"Metadata Value": metadataValues,
"Mention Text": mentionText,
"Mention Type": mentionType
}
df = pd.DataFrame(data)
df
df.to_csv("SentimentAnalysis.csv", encoding='utf-8', index=False)
def main():
import argparse
#read the csv file containing the post text we need to analyze
filename = open('Essential Data_posts.csv', 'r')
#create dictreader object
file = csv.DictReader(filename)
postTexts = []
#iterate over each column and append values to list
for col in file:
postTexts.append(col['Post Text'])
parser = arg.parse.ArgumentParser()
parser.add_argument("--postTexts", type=str, default=postTexts)
args = parser.parse_args()
sentiment_entity(args.postTexts)
【问题讨论】:
标签: python ubuntu google-cloud-platform