Google Cloud NLP情感实体分析结果未写入CSV文件问题咨询
代码问题排查及修复方案
核心错误原因
- 执行顺序错误:生成CSV文件的代码是全局执行的,早于
main函数和sentiment_entity分析函数运行,写入时所有数组还未被赋值 - 变量名错误频发:包括参数名和内部使用名不匹配、API请求参数键名错误、重名变量覆盖、未定义变量直接调用
- 缩进错误:实体元数据、实体提及的遍历代码放在实体循环外部,无法正常取值
- 列名不匹配:读取CSV时使用的列名和实际列名不一致
- 缺少主函数入口:代码未主动触发
main函数执行 - 接口参数类型错误:直接将文本列表传入Google NLP接口,接口要求传入单篇字符串文本
具体错误点说明
sentiment_entity函数参数是postTexts,内部构造文档时错误使用未定义的post_texts变量- API请求参数
encoding type拼写错误,正确应为encoding_type - 遍历实体时循环变量
entity和全局存储实体的数组entity重名,且错误调用循环变量的append方法 - 直接使用未定义的
sentiment变量,正确应为entity.sentiment - 元数据、提及遍历代码缩进错误,未放在实体遍历循环内部
- 读取CSV列名写为
Post Text,和你实际的Post Texts列名不符 argparse调用拼写错误,arg.parse应为argparse,且你已经从本地CSV读取文本,无需额外设置参数传入- 全局代码先执行CSV写入,此时分析函数还未运行,所有数组为空
修正后完整代码
from google.cloud import language_v1 import pandas as pd import csv # 存储分析结果的数组 representativeName = [] entity = [] salienceScore = [] entitySentimentScore = [] entitySentimentMagnitude = [] metadataNames = [] metadataValues = [] mentionText = [] mentionType = [] def sentiment_entity(post_text): client = language_v1.LanguageServiceClient() type_ = language_v1.Document.Type.PLAIN_TEXT language = "en" document = {"content": post_text, "type": type_, "language": language} encodingType = language_v1.EncodingType.UTF8 # 修正请求参数键名 response = client.analyze_entity_sentiment(request = {'document': document, 'encoding_type': encodingType}) # 遍历返回的实体 for ent in response.entities: representativeName.append(ent.name) # 修正重名变量问题 entity.append(language_v1.Entity.Type(ent.type_).name) salienceScore.append(ent.salience) # 修正未定义sentiment变量问题 entitySentimentScore.append(ent.sentiment.score) entitySentimentMagnitude.append(ent.sentiment.magnitude) # 缩进修正:放在实体遍历循环内 for metadata_name, metadata_value in ent.metadata.items(): metadataNames.append(metadata_name) metadataValues.append(metadata_value) # 缩进修正:放在实体遍历循环内 for mention in ent.mentions: mentionText.append(mention.text.content) mentionType.append(language_v1.EntityMention.Type(mention.type_).name) def main(): # 读取源CSV文件 with open('Essential Data_posts.csv', 'r', encoding='utf-8') as filename: file = csv.DictReader(filename) # 修正列名匹配问题,逐篇处理文本 for col in file: post_text = col['Post Texts'] sentiment_entity(post_text) # 所有分析完成后再写入结果CSV 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.to_csv("SentimentAnalysis.csv", encoding='utf-8', index=False) # 添加入口触发主函数 if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者pinkshades
相关产品推荐
相关产品推荐

