[英]Parsing a list in Python
I am trying sentiment analysis with MONKEYLEARN API in python.我正在尝试使用python中的 MONKEYLEARN API 进行情绪分析。
When I print the result I get the following response.当我打印结果时,我得到以下响应。
[{'text': 'Today is a very good weather', 'external_id': None,'error': False, 'classifications': [{'tag_name': 'Positive', 'tag_id':60333048, 'confidence': 0.987}]}]
The result if of type list
and I want to isolate only the classification results from this list that is the如果是
list
类型的结果,我只想从该列表中隔离分类结果,即
TAG_NAME: Positive and the Confidence: 0.987 TAG_NAME:积极和自信:0.987
All the answers worked efficietly.所有答案都有效。 I went with answer by AVION and Sayandip Dutta.
我接受了 AVION 和 Sayandip Dutta 的回答。
classification_result = lst[0]['classifications'][0]
tag_name = classification_result['tag_name']
confidence = classification_result['confidence']
Say you are getting the response like this:假设您收到这样的响应:
lst = [{'text': 'Today is a very good weather', 'external_id': None, 'error': False, 'classifications': [{'tag_name': 'Positive', 'tag_id': 60333048, 'confidence': 0.987}]}]
Do this:做这个:
classification_result = lst[0]['classifications'][0]
tag_name = classification_result['tag_name']
confidence = classification_result['confidence']
result = [{'text': 'Today is a very good weather', 'external_id': None, 'error': False, 'classifications': [{'tag_name': 'Positive', 'tag_id': 60333048, 'confidence': 0.987}]}]
classification_result = result[0].get("classifications")[0]
Now this is dictionary from which following can get gathered:现在这是可以从中收集以下内容的字典:
it is nested dictionary inside list, and list inside dictionary它是列表内的嵌套字典,字典内的列表
Filter looks right choice here if rs
is your result you can also wrap it in a function to avoid harcoding tag_name
and confidence
values如果
rs
是您的结果,过滤器在这里看起来是正确的选择,您也可以将其包装在 function 中以避免对tag_name
和confidence
值进行编码
rs = [{'text': 'Today is a very good weather', 'external_id': None, 'error': False, 'classifications': [{'tag_name': 'Positive', 'tag_id': 60333048, 'confidence': 0.987}]}]
filtered_result = filter(lambda record: record['classifications'][:1].get("tag_name")== 'Positive' and record['classifications'][:1].get('confidence') == 0.987,rs)
list(filtered_result)
Just get the element you from the list and then select classification
.只需从列表中获取您的元素,然后 select
classification
。 You can easily this if you print your list.如果你打印你的列表,你可以很容易地做到这一点。
your_list = [{'text': 'Today is a very good weather', 'external_id': None,'error': False, 'classifications': [{'tag_name': 'Positive', 'tag_id':60333048, 'confidence': 0.987}]}]
print(your_list)
#output
[{'text': 'Today is a very good weather',
'external_id': None,
'error': False,
'classifications': [{'tag_name': 'Positive',
'tag_id': 60333048,
'confidence': 0.987}]}]
Then do this然后这样做
your_list[0]['classifications']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.