2018/06/12

[python] text from url

import requests
import json
url = 'http://www.quotesondesign.com/wp-json/posts'
resp = requests.get(url)

# srting to Python data type
c_lst = json.loads(resp.text)

for txt in c_lst:
    # unpacking
    for key, value in txt.items():
        print(key, ' : ', value)

2018/06/11

[python] json

import json

# Json String to variable
sample = {
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

# string to Json encoding with formatting
sample_json = json.dumps(sample, indent = 4)
print(sample_json)
print('')

# Decoding Json String to Python type
sample_structured_json = json.loads(sample_json)
print(sample_structured_json)
print('')

print(sample_structured_json['glossary']['title'])
print('')

for i in sample_structured_json['glossary']['GlossDiv']['GlossList']['GlossEntry']:
    print(i)

2018/06/08

[python] binary data write to file

# binary data generation
bdata = bytes(range(0, 256))

# check length and data
print('size :', len(bdata), '\ndata : ', bdata)

# set offset and chunk size, get data size
offset = 0
chunk = 10
size = len(bdata)

# write to file and get size
with open('bfile.bin', 'wb') as bf:
    while offset <= size:
        bf.write(bdata[offset:offset+chunk])
        offset += chunk

# check file
! cat bfile.bin