Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Can';t打印Stocktwits字典的键_Python_Json_Dictionary - Fatal编程技术网

Python Can';t打印Stocktwits字典的键

Python Can';t打印Stocktwits字典的键,python,json,dictionary,Python,Json,Dictionary,我正在学习从Stocktwit的API获取数据,目前正在探索API的数据。我执行了以下代码来提取最近30条关于苹果股票的推文的信息: import requests a=requests.get('https://api.stocktwits.com/api/2/streams/symbol/AAPL.json') a=a.json() print(a.keys()) >> dict_keys(['cursor', 'messages', 'response', 'symbol']

我正在学习从Stocktwit的API获取数据,目前正在探索API的数据。我执行了以下代码来提取最近30条关于苹果股票的推文的信息:

import requests

a=requests.get('https://api.stocktwits.com/api/2/streams/symbol/AAPL.json')
a=a.json()
print(a.keys())
>> dict_keys(['cursor', 'messages', 'response', 'symbol'])
我可以看到苹果的股票字典里有四个键。然而,我看不到情绪的关键,这基本上就是我要寻找的:关键词“看涨”出现了多少次?“熊市”这个词出现了多少次

如果我直接从浏览器手动输入,我可以手动查看苹果股票上出现了多少次“看跌”和“看涨”关键字。如何使用Python 3.5实现这一点

编辑:我甚至试着按照作者的建议在字典的一个键中查找我的关键字 邮局


看起来,
a[看跌]
可能是另一本字典
print()
自动插入空格,为什么不将print语句更改为

print ("the key name is", bearish, "and its value is", a[bearish])
这将使调试这里发生的事情变得更容易。

您应该使用而不是
+
来解决您的问题

查看以下内容以了解
format()
的作用:

>>> my_dict = {'a': {'aa': 10}, 'b': {'bb': 20}}
>>>
>>> for key in my_dict.keys():
...     print "key :" + key + " and value: " + my_dict[key]
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: cannot concatenate 'str' and 'dict' objects
>>>
>>> for key in my_dict.keys():
...     print "key : {} and value: {}".format(key, my_dict[key])
...
key : a and value: {'aa': 10}
key : b and value: {'bb': 20}
>>my_dict={'a':{'aa':10},'b':{'bb':20}
>>>
>>>对于my_dict.keys()中的键:
...     打印“键:+key+”和值:+my_dict[key]
...
回溯(最近一次呼叫最后一次):
文件“”,第2行,在
TypeError:无法连接'str'和'dict'对象
>>>
>>>对于my_dict.keys()中的键:
...     打印“key:{}和value:{}”。格式(key,my_dict[key])
...
键:a和值:{'aa':10}
键:b和值:{'bb':20}

情感隐藏在
信息中

from collections import Counter
sentiment_dict = Counter()
for message in a['messages']:
    if 'entities' in message:
        if 'sentiment' in message['entities']:
            sentiment = message['entities']['sentiment']
            if sentiment is not None:
                sentiment = sentiment['basic']
                sentiment_dict[sentiment] += 1
for key, value in sentiment_dict.items():
    print "%s: %s" % (key, value)
输出

Bearish: 4
Bullish: 8
我使用了
计数器
,这是
dict
的一个特化,来计算情感的频率

注意

对于其他试图在JSON中查找字段的人,我建议

import json
print json.dumps(a, indent=4)

令人惊叹的!您介意建议我使用什么Python函数或方法来计算“看跌”和“看涨”出现的次数吗?我修改了示例,使用了
计数器
类。
import json
print json.dumps(a, indent=4)