Python — Fedorishev.ru http://fedorishev.ru записная книжка Sat, 30 Jan 2016 08:26:48 +0000 ru-RU hourly 1 Make a list of similar urls like www.example.com/page=10 http://fedorishev.ru/2015/10/make-a-list-of-similar-urls-like-www-example-compage10/ http://fedorishev.ru/2015/10/make-a-list-of-similar-urls-like-www-example-compage10/#respond Wed, 14 Oct 2015 11:39:54 +0000 http://fedorishev.ru/?p=138 1. Make a column of incrementing numbers
:put =range(1,50)
2
.
Use Ctrl+V to select the first column of text in the lines you want to comment.
Then hit Shift+i and type the text you want to insert. (www.example.com/page=)
Then hit Esc, wait 1 second and the inserted text will appear on every line.
Voila

]]>
http://fedorishev.ru/2015/10/make-a-list-of-similar-urls-like-www-example-compage10/feed/ 0
исправить кодировки имен файлов Ubuntu http://fedorishev.ru/2015/04/%d0%b8%d1%81%d0%bf%d1%80%d0%b0%d0%b2%d0%b8%d1%82%d1%8c-%d0%ba%d0%be%d0%b4%d0%b8%d1%80%d0%be%d0%b2%d0%ba%d0%b8-%d0%b8%d0%bc%d0%b5%d0%bd-%d1%84%d0%b0%d0%b9%d0%bb%d0%be%d0%b2-ubuntu/ http://fedorishev.ru/2015/04/%d0%b8%d1%81%d0%bf%d1%80%d0%b0%d0%b2%d0%b8%d1%82%d1%8c-%d0%ba%d0%be%d0%b4%d0%b8%d1%80%d0%be%d0%b2%d0%ba%d0%b8-%d0%b8%d0%bc%d0%b5%d0%bd-%d1%84%d0%b0%d0%b9%d0%bb%d0%be%d0%b2-ubuntu/#respond Fri, 17 Apr 2015 10:54:28 +0000 http://fedorishev.ru/?p=126 sudo apt-get install convmv
find . -type f -print -exec convmv —notest -f -t {} \;

UPD: Неприятный случай с «doubly-encoded to utf-8 from iso-8859-5»

#-*-coding:utf8-*-
import os
allfiles=[]
for root, dirs, files in os.walk("./", topdown=False):
for name in files:
allfiles.append(os.path.join(root, name))

for f in allfiles:
try:
newf=f.decode('utf8').encode('latin1').decode('utf8', 'replace')
except:
print "{} is in proper encoding".format(f)
else:
os.rename(f, newf)
print "{} decoded well".format(f)

]]>
http://fedorishev.ru/2015/04/%d0%b8%d1%81%d0%bf%d1%80%d0%b0%d0%b2%d0%b8%d1%82%d1%8c-%d0%ba%d0%be%d0%b4%d0%b8%d1%80%d0%be%d0%b2%d0%ba%d0%b8-%d0%b8%d0%bc%d0%b5%d0%bd-%d1%84%d0%b0%d0%b9%d0%bb%d0%be%d0%b2-ubuntu/feed/ 0
pretty print nested dict with unicode values http://fedorishev.ru/2015/04/pretty-print-nested-dict-with-unicode-values/ http://fedorishev.ru/2015/04/pretty-print-nested-dict-with-unicode-values/#respond Wed, 15 Apr 2015 14:51:42 +0000 http://fedorishev.ru/?p=124 >> import json >>> print json.dumps({}, sort_keys=True, indent=4, ensure_ascii=False) http://stackoverflow.com/questions/3229419/pretty-printing-nested-dictionaries-in-python]]> >>> import json
>>> print json.dumps({}, sort_keys=True, indent=4, ensure_ascii=False)

http://stackoverflow.com/questions/3229419/pretty-printing-nested-dictionaries-in-python

]]>
http://fedorishev.ru/2015/04/pretty-print-nested-dict-with-unicode-values/feed/ 0
dict to class — рекурсивно http://fedorishev.ru/2014/04/dict-to-class-%d1%80%d0%b5%d0%ba%d1%83%d1%80%d1%81%d0%b8%d0%b2%d0%bd%d0%be/ http://fedorishev.ru/2014/04/dict-to-class-%d1%80%d0%b5%d0%ba%d1%83%d1%80%d1%81%d0%b8%d0%b2%d0%bd%d0%be/#respond Tue, 29 Apr 2014 18:59:23 +0000 http://fedorishev.ru/?p=109 # convert a dictionary to a class
class Struct(object):
def __init__(self, adict):
"""Convert a dictionary to a class

@param :adict Dictionary
"""
self.__dict__.update(adict)
for k, v in adict.items():
if isinstance(v, dict):
self.__dict__[k] = Struct(v)

def get_object(adict):
"""Convert a dictionary to a class

@param :adict Dictionary
@return :class:Struct
"""
return Struct(adict)

Рецепт:

]]>
http://fedorishev.ru/2014/04/dict-to-class-%d1%80%d0%b5%d0%ba%d1%83%d1%80%d1%81%d0%b8%d0%b2%d0%bd%d0%be/feed/ 0
Рекурсивное обновление словарей http://fedorishev.ru/2014/02/%d1%80%d0%b5%d0%ba%d1%83%d1%80%d1%81%d0%b8%d0%b2%d0%bd%d0%be%d0%b5-%d0%be%d0%b1%d0%bd%d0%be%d0%b2%d0%bb%d0%b5%d0%bd%d0%b8%d0%b5-%d1%81%d0%bb%d0%be%d0%b2%d0%b0%d1%80%d0%b5%d0%b9/ http://fedorishev.ru/2014/02/%d1%80%d0%b5%d0%ba%d1%83%d1%80%d1%81%d0%b8%d0%b2%d0%bd%d0%be%d0%b5-%d0%be%d0%b1%d0%bd%d0%be%d0%b2%d0%bb%d0%b5%d0%bd%d0%b8%d0%b5-%d1%81%d0%bb%d0%be%d0%b2%d0%b0%d1%80%d0%b5%d0%b9/#respond Fri, 14 Feb 2014 12:36:18 +0000 http://fedorishev.ru/?p=104 def rUpdate(targetDict, itemDict):
«Recursively updates nested dicts»
for key, val in itemDict.items():
if type(val) == type({}):
newTarget = targetDict.setdefault(key,{})
rUpdate(newTarget, val)
else:
targetDict[key] = val

]]>
http://fedorishev.ru/2014/02/%d1%80%d0%b5%d0%ba%d1%83%d1%80%d1%81%d0%b8%d0%b2%d0%bd%d0%be%d0%b5-%d0%be%d0%b1%d0%bd%d0%be%d0%b2%d0%bb%d0%b5%d0%bd%d0%b8%d0%b5-%d1%81%d0%bb%d0%be%d0%b2%d0%b0%d1%80%d0%b5%d0%b9/feed/ 0
Считаем непустые элементы в списке http://fedorishev.ru/2014/02/%d1%81%d1%87%d0%b8%d1%82%d0%b0%d0%b5%d0%bc-%d0%bd%d0%b5%d0%bf%d1%83%d1%81%d1%82%d1%8b%d0%b5-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d1%8b-%d0%b2-%d1%81%d0%bf%d0%b8%d1%81%d0%ba%d0%b5/ http://fedorishev.ru/2014/02/%d1%81%d1%87%d0%b8%d1%82%d0%b0%d0%b5%d0%bc-%d0%bd%d0%b5%d0%bf%d1%83%d1%81%d1%82%d1%8b%d0%b5-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d1%8b-%d0%b2-%d1%81%d0%bf%d0%b8%d1%81%d0%ba%d0%b5/#respond Thu, 13 Feb 2014 11:06:29 +0000 http://fedorishev.ru/?p=99 len(filter(None, iterable))

]]>
http://fedorishev.ru/2014/02/%d1%81%d1%87%d0%b8%d1%82%d0%b0%d0%b5%d0%bc-%d0%bd%d0%b5%d0%bf%d1%83%d1%81%d1%82%d1%8b%d0%b5-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d1%8b-%d0%b2-%d1%81%d0%bf%d0%b8%d1%81%d0%ba%d0%b5/feed/ 0
SQLFORM.grid — коробочный настраиваемый броузер таблиц http://fedorishev.ru/2013/10/sqlformgrid/ http://fedorishev.ru/2013/10/sqlformgrid/#respond Wed, 30 Oct 2013 17:01:56 +0000 http://fedorishev.ru/?p=72 Быстро вывести табличку с базой данных поможет такая простая конструкция в web2py :

grid = SQLFORM.grid(db.table)

А вот и параметры ее

SQLFORM.grid(
query,
fields=None, # выборка полей для вывода
field_id=None, # id - поле
left=None, # LEFT JOIN
headers={}, # Заголовки
orderby=None, # сортировка
groupby=None, # группировка
searchable=True, # поле поиска
sortable=True, # кнопки сортировки
paginate=20, # записей на страницу
deletable=True, # кнопка удалить
editable=True, # кнопка редактировать
details=True, # кнопка Подробнее
selectable=None, # чекбокс для выбора
create=True, # можно создавать новые элементы
csv=True, # экспорт в csv
links=None, # поля - ссылки
links_in_grid=True, # показывать в главной таблице ссылки
upload='<default>', #
args=[], #
user_signature=True, #
maxtextlengths={}, # максимальная длина текста в полях
maxtextlength=20, #
onvalidation=None, # функция вызываемая при проверке формы
oncreate=None, # функция при создании нового элемента
onupdate=None, # функция при редактировании элемента
ondelete=None, # функция при удалении элемента
sorter_icons=(XML('&#x2191;'), XML('&#x2193;')), # иконки сортировки
ui = 'web2py', # можно поставить jquery-ui, либо описать все компоненты индивидуально словарем
showbuttontext=True, # Текст на кнопках
_class="web2py_grid", # класс формы
formname='web2py_grid', # имя формы
search_widget='default', # поисковая форма
ignore_rw = False, #
formstyle = 'table3cols', #
exportclasses = None, #
formargs={}, # аргументы формы
createargs={}, # аргументы функции создания нового элемента
editargs={}, # аргументы функции редактирования элемента
viewargs={}, # аргументы функции просмотра элемента
buttons_placement = 'right', # кнопки справа
links_placement = 'right' # ссылки справа
)

Credits : http://www.web2py.com/book/default/chapter/07#SQLFORM.grid

]]>
http://fedorishev.ru/2013/10/sqlformgrid/feed/ 0
logging : пишем логи в файл http://fedorishev.ru/2013/10/logging/ http://fedorishev.ru/2013/10/logging/#respond Wed, 30 Oct 2013 09:32:28 +0000 http://fedorishev.ru/?p=66 Выводим время, уровень ошибки, файл и строку вызова, ну и естественно, текст сообщения:

import logging
logging.basicConfig(format = u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s', level = logging.DEBUG,  filename = u'applog.log')

logging.debug('This is just a debug')

via http://habrahabr.ru/post/144566/

upd: лучший пример со stackoverfow :

import logging
log = logging.getLogger("mylog")
log.setLevel(logging.DEBUG)

formatter = logging.Formatter(
    "%(asctime)s %(threadName)-11s %(levelname)-10s %(message)s")
# Alternative formatting available on python 3.2+:
# formatter = logging.Formatter(
#     "{asctime} {threadName:>11} {levelname} {message}", style='{')

# Log to file
filehandler = logging.FileHandler("debug.txt", "w")
filehandler.setLevel(logging.DEBUG)
filehandler.setFormatter(formatter)
log.addHandler(filehandler)

# Log to stdout too
streamhandler = logging.StreamHandler()
streamhandler.setLevel(logging.INFO)
streamhandler.setFormatter(formatter)
log.addHandler(streamhandler)

# Test it
log.debug("Some message")
log.error("An error!")
try:
    something()
except:
    log.exception("An exception occured!")

via http://stackoverflow.com/questions/4722745/logging-between-classes-in-python

 

]]>
http://fedorishev.ru/2013/10/logging/feed/ 0
scrapy — кроулим, парсим и грабим http://fedorishev.ru/2013/10/scrapy/ http://fedorishev.ru/2013/10/scrapy/#respond Tue, 22 Oct 2013 17:44:53 +0000 http://fedorishev.ru/?p=58 scrapy — весьма ценная библиотека для тех, кому нужно пройти по большому массиву страниц (с большой вложенностью, заранее не ограниченному), и добыть оттуда набор однотипной информации.

В общем, пойди туда — пока не знаю куда, принеси то — пока не знаю что. И сформируй из этого таблицу csv или файл json.

pip install scrapy
# создаем новый проект - ScrapySample
scrapy startproject ScrapySample

Редактируем конфигурационные файлы. Сначала что собирать — файл item.py в папке webcrawl

from scrapy.item import Item, Field
class ScrapySample(Item):
    title = Field()
    link = Field() 
    content = Field() 
    pass

Теперь сам паук. В папкe ScrapySample/spiders создаем ScrapySpider.py

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http.request import Request
from scrapy_sample.items import ScrapySampleItem

class ScrapyOrgSpider(BaseSpider):
    name = "scrapy"
    allowed_domains = ["scrapy.org"]
    start_urls = ["http://blog.scrapy.org/"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)

        next_page = hxs.select("//div[@class='pagination']/a[@class='next_page']/@href").extract()
        if next_page:
            yield Request(next_page[0], self.parse)

        posts = hxs.select("//div[@class='post']")
        items = []
        for post in posts:
            item = ScrapySampleItem()
            item["title"] = post.select("div[@class='bodytext']/h2/a/text()").extract()
            item["link"] = post.select("div[@class='bodytext']/h2/a/@href").extract()
            item["content"] = post.select("div[@class='bodytext']/p/text()").extract()
            items.append(item)
        for item in items:
            yield item
            # возвращаем генератор собранных объектов

Запускаем:

scrapy crawl ScrapySample -o ScrapySample.json -t json

(можно в csv или xml)

Thanks :

http://amaral.northwestern.edu/blogs/2013/apr/8/quick-introduction-web-crawling-using-scrapy-part-/

https://github.com/milinda/Scrapy-Sample/blob/0a8ffba73f5f31b2a37d87530ceb341e7302182d/scrapy_sample/spiders/ScrapySpider.py

]]>
http://fedorishev.ru/2013/10/scrapy/feed/ 0
dataset — еще одна обертка баз данных для ленивых http://fedorishev.ru/2013/10/dataset/ http://fedorishev.ru/2013/10/dataset/#respond Tue, 15 Oct 2013 14:42:07 +0000 http://fedorishev.ru/?p=52 import dataset db = dataset.connect('sqlite:///:memory:') table = db['sometable'] table.insert(dict(name='John Doe', age=37)) table.insert(dict(name='Jane Doe', age=34, gender='female')) john = table.find_one(name='John Doe') # Внимание, теперь самое вкусное! # Запросы: table = db['users'].table statement = table.select(table.c.name.like('%Snoopy%')) result = db.query(statement) # Сохраняем в json/csv всех result = db['users'].all() dataset.freeze(result, 'users.json', format='json') # Или каждого пользователя в свой файл # export one JSON file per user dataset.freeze(result, 'users/{{ id }}.json', format='json', mode='item')

via https://dataset.readthedocs.org/en/latest/

]]>
http://fedorishev.ru/2013/10/dataset/feed/ 0