Joe Taylor Joe Taylor - 23 days ago 5
JSON Question

Split words into variables

I'm reading an MP3 radio stream using Python and it prints out something like this


I'd like to separate the words and place them in their own table / field.

The above is Artist, SongName, RadioStation, MUSIC, some number which I don't know what it is and doesn't ever change.

I've found something called word split but unsure if that will work.

I'm also unsure if a space in the song or artist name will cause any problems. The space isn't an underscore or anything clever, it is literally a space.

#!/usr/bin/env python
import urllib2
import datetime
import requests

stream_url = 'http://stream....'
request = urllib2.Request(stream_url)
request.add_header('Icy-MetaData', 1)
response = urllib2.urlopen(request)
icy_metaint_header = response.headers.get('icy-metaint')
if icy_metaint_header is not None:
metaint = int(icy_metaint_header)
read_buffer = metaint+512
content =
title = content[metaint:].split("'")[1]
print title
# post_data = {'artist':'////', 'songname':'/////'}
# post_response ='http:///////', data=post_data)
import json

print 'null'
# print 'Error'
# print


You want to use the string's split method:

stream = "INXS~Disappear~RADIOSTATION~~MUSIC~~~360000~~~"
parts = stream.split("~")

with python it's even possible to directly assign the list elements returned by the split method to specific variables:

artist, songname, radiostation, music, number = [x for x in stream.split("~") if x]

I used a simple list comprehension to get rid of the empty elements in the list.

Instead of using a list comprehension you could use the filter built-in function to remove the empty elements:

 artist, songname, radiostation, music, number = filter(len, stream.split("~"))