我有一些示例代碼,可以使用 Google 的自然語(yǔ)言 API 來(lái)分析實(shí)體及其情緒。對(duì)于 Pandas 數(shù)據(jù)框中的每條記錄,我想返回一個(gè)字典列表,其中每個(gè)元素都是一個(gè)實(shí)體。然而,當(dāng)我嘗試讓它在生產(chǎn)數(shù)據(jù)上工作時(shí)遇到了問(wèn)題。這是示例代碼from google.cloud import language_v1 # version 2.0.0import os os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path/to/json'import pandas as pd # establish client connectionclient = language_v1.LanguageServiceClient()# helper function def custom_analyze_entity(text_content): global client #print("Accepted Input::" + text_content) document = language_v1.Document(content=text_content, type_=language_v1.Document.Type.PLAIN_TEXT, language = 'en') response = client.analyze_entity_sentiment(request = {'document': document}) # a document can have many entities # create a list of dictionaries, every element in the list is a dictionary that represents an entity # the dictionary is nested l = [] #print("Entity response:" + str(response.entities)) for entity in response.entities: #print('=' * 20) temp_dict = {} temp_meta_dict = {} temp_mentions = {} temp_dict['name'] = entity.name temp_dict['type'] = language_v1.Entity.Type(entity.type_).name temp_dict['salience'] = str(entity.salience) sentiment = entity.sentiment temp_dict['sentiment_score'] = str(sentiment.score) temp_dict['sentiment_magnitude'] = str(sentiment.magnitude) for metadata_name, metadata_value in entity.metadata.items(): temp_meta_dict['metadata_name'] = metadata_name temp_meta_dict['metadata_value'] = metadata_value temp_dict['metadata'] = temp_meta_dict for mention in entity.mentions: temp_mentions['mention_text'] = str(mention.text.content) temp_mentions['mention_type'] = str(language_v1.EntityMention.Type(mention.type_).name) temp_dict['mentions'] = temp_mentions #print(u"Appended Entity::: {}".format(temp_dict)) l.append(temp_dict) return l
1 回答

慕后森
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
嘗試這樣做:
input_df.loc[0, 'entity_object'] = ""
for i in range(len(input_df)):
op = custom_analyze_entity(input_df.loc[i,'freeform_text'])
input_df.loc[i, 'entity_object'] = op
或者對(duì)于您的具體情況,您不需要使用loc函數(shù)。
input_df["entity_object"] = ""
for i in range(len(input_df)):
op = custom_analyze_entity(input_df.loc[i,'freeform_text'])
input_df["entity_object"][i] = op
添加回答
舉報(bào)
0/150
提交
取消