>>> data = urlopen('http://devcave.ru/json.php').read()
>>> data.decode('utf-8')
u'{"key":"\\u0440\\u0443\\u0441\\u0441\\u043a\\u0438\\u0439 \\u044f\\u0437\\u044b\\u043a"}'
>>> data.decode('cp1251')
u'{"key":"\\u0440\\u0443\\u0441\\u0441\\u043a\\u0438\\u0439 \\u044f\\u0437\\u044b\\u043a"}'
import re
filter(None, re.split('\s', text))
[entry.strip() for line in text.splitlines() for entry in line.split()]
def tokenize(data):
cleanup = lambda entry: entry.replace(':', '').strip()
for entry in data.strip(';').split(';'):
entry = map(cleanup, entry.rsplit(':',1))
if len(entry) == 1:
entry.append(True)
yield entry
input = 'name1: value1; name2: value2; name3; prefix: name4: value4;'
print dict(tokenize(input))
{'prefix name4': 'value4', 'name2': 'value2', 'name3': True, 'name1': 'value1'}
>>> dict(re.findall('\s*([\w\s:]+?)\s*(?::\s*([\w\s]*)\s*)?(?=[;$])', input))
{'prefix: name4': 'value4', 'name2': 'value2', 'name3': '', 'name1': 'value1'}
>>> import re
>>> text = '[br][img src="images/20150429064557608.jpg" width="1500" class="class_name" alt="pic_title"][br]'
>>> items = re.findall(r'(?:\b(src|width|class|alt)="([^"]*)")+', text)
>>> items
[('src', 'images/20150429064557608.jpg'), ('width', '1500'), ('class', 'class_name'), ('alt', 'pic_title')]
>>> line = '<img %s>' % ' '.join('%s="%s"' % (param, value) for param, value in items)
>>> line
'<img src="images/20150429064557608.jpg" width="1500" class="class_name" alt="pic_title">'
import urllib, re
html = urllib.urlopen('http://www.mail.ru/').read()
pattern = '<span class="weather__temperature">([-+\d]+)</span>',
temperature = re.search(pattern, html).group(1)
print temperature
def checksum(code, awards={'A': 15, 'B': 20, 'C': 30, '': 40}, joker='D'):
return sum(
awards.get(''.join(set(triplet)-{joker}), 0) for triplet in zip(*[iter(code)]*3)
)
checksum('ABCAABDCA') # 0
checksum('ADAAABDCA') # 15
def checksum2(code, awards={'A': 15, 'B': 20, 'C': 30, '': 40}, joker='D'):
return reduce(
lambda xsum, triplet: xsum + awards.get(
''.join(set(triplet).difference(joker)), 0
),
(code[0:3], code[3:6], code[6:9]), 0
)
html = urllib.request.urlopen(url).read().decode('utf-8').encode('cp1251')
audio = (
{'lyrics_id': 3586866, 'title': 'Fruhling in Paris', 'id': 358450897, 'artist': 'Rammstein', 'owner_id': 358450897},
{'lyrics_id': 3655472, 'title': 'Zwitter', 'id': 358450894, 'artist': 'Rammstein', 'owner_id': 358450897},
)
keys_to_delete = {'owner_id', 'duration', 'url', 'lyrics_id', 'album_id', 'genre_id'}
for track in audio:
for attribute in keys_to_delete:
try:
del track[attribute]
except KeyError:
pass
>>> def foo(**kwargs):
kwargs['id'] = 1
print 'Internal: %s' % kwargs['id']
>>> d = {'id': 0}
>>> foo(**d)
Internal: 1
>>> d
{'id': 0}
>>> def foo(**kwargs):
kwargs['id'][:] = [4, 5, 6]
print 'Internal: %s' % kwargs['id']
>>> d = {'id': [1, 2, 3]}
>>> foo(**d)
Internal: [4, 5, 6]
>>> d
{'id': [4, 5, 6]}
from random import random
while True:
try:
total = int(raw_input('\nВведите количество бросков: '))
except ValueError:
print 'Введено некорректное значение: ожидается целое число.'
else:
# side1 = sum(random() < 0.5 for n in xrange(total))
side1 = int(round(sum(random() for n in xrange(total)))) # эквивалент random() >= 0.5
side2 = max(0, total) - side1
print 'Результат: орёл - {0}, решка - {1}'.format(side1, side2)
finally:
if raw_input('\nПопробовать ещё раз (Y)? ').upper() != 'Y':
break
import collections, random
options = ('орёл', 'решка')
while True:
stats = collections.Counter(dict.fromkeys(options, 0))
try:
stats.update(
random.choice(options) for test in xrange(
input('\nВведите количество бросков: ')
)
)
except:
print 'Введено некорректное значение: ожидается целое число.'
else:
print 'Результат: {0} - {{{0}}}, {1} - {{{1}}}'.format(*options).format(**stats)
finally:
if raw_input('\nПопробовать ещё раз (Y)? ').upper() != 'Y':
break
>>> timeit('choice((0,1))', setup='from random import random, choice', number=10**6)
1.4363103769230747
>>> timeit('random() < 0.5', setup='from random import random, choice', number=10**6)
0.18878976080804932
>>> exec('xyz="xyz"')
>>> xyz
'xyz'
>>> exec('{s}="{s}"'.format(s='xyz'))
>>> xyz
'xyz'
$ echo '<img src="./images/flags/AZ.png">Azaza</p>' | grep -oP '(?<=\.png">)(\w+)(?=</p>)'
Azaza