简体   繁体   English

Python-数据分割和提取

[英]Python - Data Splitting and Extraction

I am using the Twitch API and i am having issues in understanding how to extract data from it. 我正在使用Twitch API,在理解如何从中提取数据时遇到问题。

I call the API and this is the sort of response i get: 我调用了API,这是我得到的响应:

"name":"user1", "game":"game1","name":"user2", "game":"game2"

I know i will need to use some .split() 's but i cannot work out how as each time i try i get a blank output. 我知道我将需要使用一些.split() ,但是我无法确定每次尝试时如何获得空白输出。

The data i need is the user1 , game1 , user2 , game2 我需要的数据是user1game1user2game2

This data is repeated several times and i cannot find out how to extract this data from the mass of other data given. 此数据重复了几次,我无法找出如何从给定的其他大量数据中提取此数据。

Any links or advice will be grateful, i cannot find any reference to large data extraction like this 任何链接或建议将不胜感激,我找不到这样的大数据提取参考

EDIT 编辑

After being advised it was json data i edited the code to parse it appropriately. 在被告知是json数据后,我编辑了代码以对其进行适当地解析。 But i keep getting the error: AttributeError: 'unicode' object has no attribute 'get' 但是我一直收到错误: AttributeError: 'unicode' object has no attribute 'get'

Here is the code: 这是代码:

import urllib2
import json

url = "https://api.twitch.tv/kraken/channels/'Mychannel'/follows/"

if __name__ == "__main__":
    req = urllib2.Request(url)
    opener = urllib2.build_opener()
    f = opener.open(req)
    json = json.load (f)

    for item in json:
        print item.get('name')

Any suggestions to why this error is occurring? 关于为什么会发生此错误的任何建议?

The response is json data; 响应是json数据; use the json module to parse it. 使用json模块进行解析。

assuming you are receiving a string back, such that: 假设您收到一个字符串,例如:

>>> a = '"name":"user1", "game":"game1","name":"user2", "game":"game2"'
>>> a
'"name":"user1", "game":"game1","name":"user2", "game":"game2"'

You can get your first split by doing a split by the "," 您可以通过用“,”进行拆分来进行第一次拆分

>>> mlist = a.split(",")
>>> mlist
['"name":"user1"', ' "game":"game1"', '"name":"user2"', ' "game":"game2"']

Now you can access the data of each element by looping: 现在,您可以通过循环访问每个元素的数据:

>>> for e in mlist:
    print("Data:", e.split(":")[1])

('Data:', '"user1"')
('Data:', '"game1"')
('Data:', '"user2"')
('Data:', '"game2"')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM