我正在致力于将字典转换为数据帧-但数据帧不显示列格式 我希望像Image1(我做的另一个例子),但数据显示为Image2
在第一个示例(Image1)中,我使用一个URL作为新闻源 在第二个示例(Image2)中,我有一个for循环来解析新闻源的多个URL
我还看到第二个示例中的字典有2个“[]”,而第一个字典只有一个[]
我可以提供更多的细节。 如果可以的话,请帮助我
提前谢谢大家
Image1 - dictionary to pandas dataframe output shows up fine
Image2 - dictionary to pandas dataframe output DOES NOT shows up fine
enter code here
此处提取实体功能代码:
def extractEntities(url):
endpoint_watson = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze"
params = {
'version': '2020-09-12',
}
headers = {
'Content-Type': 'application/json',
}
watson_options = {
"url": url,
"features": {
"entities": {
"sentiment": True,
"emotion": True,
"limit": 100
}
}
}
username = "apikey"
password = "<<myAPIKeyinfo>>"
resp = requests.post(endpoint_watson,
data=json.dumps(watson_options),
headers=headers,
params=params,
auth=(username, password)
)
results = resp.json()
article_dict = []
if "entities" in results:
for i in results.get('entities'):
initial_dict = {}
initial_dict['entity'] = i['text']
initial_dict['url'] = url
initial_dict['source'] = url.split('.')[1]
initial_dict['relevance'] = i['relevance']
initial_dict['sentiment'] = i['sentiment']['score']
article_dict.append(initial_dict)
return article_dict
然后提取一些新闻实体
s3 = 'the-wall-street-journal'
allurls3 = []
allurls3 = getNews(s3)
allurls3
下面是调用extractEntities函数的代码。它还包含另一个for循环:
dict1 = []
for u in range(len(allurls3)):
data3 = []
url3 = allurls3[u]
data3 = extractEntities(url3)
dict1.append(data3)
dict1
谢谢你发布代码。在未来,please do not upload images of code/errors when asking a question.并尝试使其成为Minimal, Reproducible Example。我没有Watson API密钥,因此无法完全复制您的示例,但is的基本功能如下:
在
extractEntities(url)
中,您对Watson NLP服务进行API调用,并为响应中找到的每个实体创建一个具有相关性、情感等的字典。最后返回所有这些词典的列表。根据您提供的代码,让我们创建一个虚拟函数来模拟它,以便我可以尝试重现您遇到的问题示例输出是字典列表:
现在
allurls3
中有一个URL列表,并执行以下操作:dict1
的空列表allurls3
中循环URLextractEntities
,data3
现在拥有一个字典列表(见上文)dict1
。 最终结果dict1
是字典列表:最后,将这个字典列表
dict1
包装到另一个列表中,将其转换为一个数据帧好的,现在我已经能够重现你的错误,我可以告诉你如何修复它。从您发布的第一张图片中可以看出,您需要向
pd.DataFrame
提供字典列表,而不是像现在这样提供字典列表列表此外,命名一个列表} instead of ^{}
dict1
非常令人困惑。因此,请执行以下操作。关键的区别是使用^{现在,您有了一个字典列表,可用于创建数据帧:
相关问题 更多 >
编程相关推荐