'Data/Text/Knowledge Analysis & Mining/Python'에 해당하는 글 24건

python 및 머신러닝 교육, 슬로우캠퍼스


HTTP redirect 처리하기

curl 명령어로 redirect가 발생하는 지 확인할 수 있다.  --head 옵션을 사용한다.

curl --head  http://j.mp/174gpKP

HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Thu, 05 Jun 2014 04:21:44 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Cache-Control: private; max-age=90
Content-Length: 153
Location: http://nolboo.github.io/blog/2013/10/17/start-blog-with-harp/
Mime-Version: 1.0
Set-Cookie: _bit=538ff058-00317-06caf-3b1cf10a;domain=.j.mp;expires=Tue Dec  2 04:21:44 2014;path=/; HttpOnly



http://j.mp/174gpKP 이라는 short URL의 원본 URL을 알고 싶다면

HTTP 301 redirect를 처리할 수 있어야 한다.  (302, 303 등도 있음)



>>> import urllib

>>> a = urllib.urlopen("http://j.mp/174gpKP")

>>> a.geturl()
'http://nolboo.github.io/blog/2013/10/17/start-blog-with-harp/'


urllib2를 이용한 방법도 있지만, 조금 복잡하다. class 정의 필요.

http://www.diveintopython.net/http_web_services/redirects.html




'Data/Text/Knowledge Analysis & Mining > Python' 카테고리의 다른 글

mechanize 예시  (0) 2013.10.18
[Git] 기본 설정 및 사용  (0) 2013.07.30
python pdf - reportlab  (0) 2013.07.26
OCR + python  (0) 2013.07.26
python pdf library 비교  (0) 2013.07.26

WRITTEN BY
manager@
Data Analysis, Text/Knowledge Mining, Python, Cloud Computing, Platform

,

python 및 머신러닝 교육, 슬로우캠퍼스

잘 설명된 곳

http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/




간단 코드


import mechanize
import urllib
import random

class Transaction(object):
        def run(self):
                br = mechanize.Browser()
                br.set_handle_robots(False)
                resp = br.open('http://aaa.com/')
                resp.read()

'Data/Text/Knowledge Analysis & Mining > Python' 카테고리의 다른 글

python 에서 http redirect 처리하기 (short url 처리)  (0) 2014.03.20
[Git] 기본 설정 및 사용  (0) 2013.07.30
python pdf - reportlab  (0) 2013.07.26
OCR + python  (0) 2013.07.26
python pdf library 비교  (0) 2013.07.26

WRITTEN BY
manager@
Data Analysis, Text/Knowledge Mining, Python, Cloud Computing, Platform

,

python 및 머신러닝 교육, 슬로우캠퍼스


git repository 다운로드 받기 - 방법 1 

$ git clone  https://github.com/user/aaa.git

$ git remote -v


git repository 다운로드 받기 - 방법 2

$ mkdir aaa

$ cd aaa

$ git init

$ git remote add origin https://github.com/user/aaa.git

$ git pull origin

$ git remote -v



기본 환경 설정하기


$ git config --global user.name "John Doe" $ git config --global user.email johndoe@example.com


# git commit 시의 editor를 뭘로 할지 설정

$ git config --global core.editor vi



git commit 시에 add에서 제외할 파일 확장자 지정하기

git config --global core.excludesfile ~/.gitignore_global



~/.gitignore_global 을 편집하여 아래와 같은 확장자들을 지정할 수 있다.
#Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so

# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip

# Logs and databases #
######################
*.log
*.sql
*.sqlite

# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db


git 소스 파일 추가 & Commit & Push 


$ vi xxx

$ git add xxx

$ git commit -a

vi로 commit log 편집후에 


$ git push origin master




http://git-scm.com/book/en/Customizing-Git-Git-Configuration


'Data/Text/Knowledge Analysis & Mining > Python' 카테고리의 다른 글

python 에서 http redirect 처리하기 (short url 처리)  (0) 2014.03.20
mechanize 예시  (0) 2013.10.18
python pdf - reportlab  (0) 2013.07.26
OCR + python  (0) 2013.07.26
python pdf library 비교  (0) 2013.07.26

WRITTEN BY
manager@
Data Analysis, Text/Knowledge Mining, Python, Cloud Computing, Platform

,

python 및 머신러닝 교육, 슬로우캠퍼스


pdf 텍스트 읽기

PDFMiner - http://www.unixuser.org/~euske/python/pdfminer/



http://redjonathan.blogspot.kr/2013/06/reportlab-python-pdf.html



한글 또는 유니코드


사용법은 어렵지 않다. 매뉴얼도 잘 되어있다. 아무래도 한글이 잘 찍히느냐가 관심사일 것이다. 잘 된다. 글꼴 지정만 잘 해주면 된다. 아스키로만 된 문서를 찍는 기본적인 튜토리얼은 생략하고 한글을 찍는 방법을 보자. 한글 뿐만 아니라 유니코드의 문자를 다양하게 사용하는 경우도 마찬가지이다.

#-*- coding: utf-8 -*-
# hello.py
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

pdfmetrics.registerFont(TTFont("HCR Batang", "HANBatang-LVT.ttf"))

c = canvas.Canvas("hello.pdf")
c.setFont("HCR Batang", 16)
c.drawString(100,100, u"안녕")
c.showPage()
c.save()

위 코드에 대해 몇가지 코멘트를 달면 다음과 같다.

  • 위 스크립트를 저정할 때 UTF-8 인코딩으로 저장해야한다. 한글을 직접 포함할 때 UTF-8을 사용하는 것이 좋다.
  • TTFont, pdfmetrics를 이용해 트루타입 글꼴에 이름을 부여하여 reportlab에서 사용할 수 있다.
  • 글꼴파일 확인은 Linux나 MacOSX에서는 fc-list로 확인할 수 있다. 물론 다른 방법으로 해도 되겠지만...
  • 위 예제에서는 함초롬바탕 첫가끝 글꼴을 사용하였다. 다운로드하려면: 함초롬체/GSUB @ KTUG
  • 위 예제는 Canvas를 이용한 것으로 문서를 찍는 것이 아니라 그림을 그리면서 텍스트를 추가하는 예제이다.


문서 생성


아무래도 Canvas를 이용해서 그림을 그릴 일 보다는 문서를 생성할 일이 더 많을 것 같다. 문서를 생성할 때는 platypus가 사용된다. 간단한 예제를 보면 다음과 같다. 역시 한글을 사용하려면 글꼴을 이름을 붙여 등록해야하는 것은 물론이고 ParagraphStyle에서 원하는 한글 글꼴을 사용하도록 지정하여 새로운 스타일일 만들어주어야한다. 간단한 예제를 보이면 다음과 같다. 

#-*- coding: utf-8 -*- 
# doc.py
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pagesizes import A4
from reportlab.platypus import Paragraph, SimpleDocTemplate
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

pdfmetrics.registerFont(TTFont("HCR Batang", "HANBatang.ttf"))

styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name="Hangul", fontName="HCR Batang"))

hangul1 = u"안녕하세요."
hangul2 = u"반갑습니다."

story = []
story.append(Paragraph(hangul1, style=styles["Hangul"]))
story.append(Paragraph(hangul2, style=styles["Hangul"]))
doc = SimpleDocTemplate("doc.pdf", pagesize=A4)
doc.build(story)


단락 내의 세세한 스타일 지정


위 예제에서는 Paragraph 단위로 스타일을 지정하는 것만 보았다. 한 단어만 빨간색으로 하고 싶거나 하면 어떻게 하는가? 이때는, 다른 방법이 있는지 모르겠지만, XML 태그를 이용한 스타일 마크업을 사용하는 것이 편리하다. 예를 들어 위 문서 생성 예제를 그대로 쓰는 대신에

hangul1 = u'<font color="red">안녕</font>하세요'



---

http://comments.gmane.org/gmane.comp.python.reportlab.user/10022

# font

FONT_FILE = '%s/Fonts/%s' % (os.environ['WINDIR'], 'BATANG.TTC') 
FONT_NAME = '바탕' 
pdfmetrics.registerFont(TTFont(FONT_NAME, FONT_FILE))


Then, after you have picked the style:

doc = SimpleDocTemplate("phello.pdf")
Story = [Spacer(1,2*inch)]
style = styles["Normal"]


'Data/Text/Knowledge Analysis & Mining > Python' 카테고리의 다른 글

mechanize 예시  (0) 2013.10.18
[Git] 기본 설정 및 사용  (0) 2013.07.30
OCR + python  (0) 2013.07.26
python pdf library 비교  (0) 2013.07.26
mongoDB, python, twitter Oauth  (0) 2013.07.25

WRITTEN BY
manager@
Data Analysis, Text/Knowledge Mining, Python, Cloud Computing, Platform

,

python 및 머신러닝 교육, 슬로우캠퍼스

OCR + python




PyTesser is an Optical Character Recognition module for Python. It takes as input an image or image file and outputs a string.

PyTesser uses the Tesseract OCR engine, converting images to an accepted format and calling the Tesseract executable as an external script. A Windows executable is provided along with the Python scripts. The scripts should work in other operating systems as well.

Dependencies

PIL is required to work with images in memory. PyTesser has been tested with Python 2.4 in Windows XP.

Usage Example

>>> from pytesser import *
>>> image = Image.open('fnord.tif')  # Open image object using PIL
>>> print image_to_string(image)     # Run tesseract.exe on image
fnord
>>> print image_file_to_string('fnord.tif')
fnord





'Data/Text/Knowledge Analysis & Mining > Python' 카테고리의 다른 글

[Git] 기본 설정 및 사용  (0) 2013.07.30
python pdf - reportlab  (0) 2013.07.26
python pdf library 비교  (0) 2013.07.26
mongoDB, python, twitter Oauth  (0) 2013.07.25
unicode, chatdet  (0) 2013.07.21

WRITTEN BY
manager@
Data Analysis, Text/Knowledge Mining, Python, Cloud Computing, Platform

,

python 및 머신러닝 교육, 슬로우캠퍼스

pyhton으로 pdf file 만들기



Note that the similar-appearing pyfpdf of Mariano Reingart is most comparable to ReportLab, in that both ReportLab and pyfpdf emphasize document generation. Interestingly enough, pyfpdf builds in a basic HTML->PDF converter;




pdfrw - Python library to read and write PDF files - Google Project ...

17 September 2012 

예) https://code.google.com/p/pdfrw/wiki/ExampleTools  --> Watermarking PDFs



pyfpdf - Simple PDF generation for Python (FPDF PHP port) AKA ...


Latest Relesed Version: 1.7 (August 15th, 2012) - Current Development Version: 1.7.1


예)  http://pyfpdf.googlecode.com/hg/tutorial/tuto3.pdf


pypdf --> pypdf2

http://knowah.github.io/PyPDF2/

https://github.com/knowah/PyPDF2/  - pure python




ReportLab 

https://bitbucket.org/rptlab/reportlab


 easy_install reportlab or pip install reportlab 


ReportLab 기반 예) https://docs.djangoproject.com/en/dev/howto/outputting-pdf/






'Data/Text/Knowledge Analysis & Mining > Python' 카테고리의 다른 글

python pdf - reportlab  (0) 2013.07.26
OCR + python  (0) 2013.07.26
mongoDB, python, twitter Oauth  (0) 2013.07.25
unicode, chatdet  (0) 2013.07.21
python map reduce lambda  (0) 2013.07.20

WRITTEN BY
manager@
Data Analysis, Text/Knowledge Mining, Python, Cloud Computing, Platform

,

python 및 머신러닝 교육, 슬로우캠퍼스



활용 및 배울 기술:

twitter.com OAUTH 연동, twitter API사용 하여 리소스 가져오기

  -- oauth, python tweepy.py




== 파이선 외부 라이브러리 소스 확인 위치

/usr/local/lib/python2.7/site-packages/

/usr/local/lib/python2.7/site-packages/tweepy



http://elle.atzine.com/elle/elleweb_template_fashion.iht?contId=B11_20110527_09100&menuId=M00024



mongo DB (weechat 서버 상태)

=== mong DB

port=27017

dbpath=/data/db/


== mongo DB 기동 확인 (mongo daemon 서버)

$ ps -ef | grep mongo

root      3243     1  0 Aug06 ?        00:00:06 ./mongod


== 설치 위치

/home/xxxx/bin/ 아래에 실행파일로 있음.  (컴파일, install 없이 binary만 복사해도 됨)


== 실제 mongo DB data 파일  위치

/data/db


== mongo DB 접속해 보기 (‘mongo’라고 실행하면 command를 입력할 수 있는 prompt로 들어간다)

mongo 에서는 db가 mysql의 db, collection이 table 쯤에 해당한다.

아래와 같은 순서로 입력해 본다.


# mongo

> help

> show dbs

> use weechat2  

> show collections
> db.users.find()     // users 라는 테이블 전체 레코드 보기

> db.users.find({"id":100004})     // users 라는 테이블에서 id가 10004 인 레코드 출력

> db.users.findOne()

> db.users.count()

> db.users.remove() // delete all

> db.users.insert( {“id”:100, “name”:”han”} )  // 레코드 추가

> db.users.update()  // 레코드 업데이트

> db.users.drop()   // collection (table) 전체 drop 하기



mongo와 mysql 명령어 비교   http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart



mac OS X 에서 mongo 설치하기

http://www.mongodb.org/display/DOCS/Quickstart+OS+X


mongo와 python → pymong

샘플소스



mongo명령어 prompt와 유사한 문법으로 pymong 사용 가능

import pymongo

from pymongo import Connection

connection = Connection()

db = connection.mydb1

table = db.followers

print table


table.insert({"id":"xxxxx", "flist":[("aaa", 10), ("bbb", 20)]})

c=table.find({"id": "xxxxxx"})

for cc in c:

       flist = cc["flist"]

      print flist



table = db.twitter

print table

table.insert({"id":"xxxxxx", "flist":[("aaa", 10), ("bbb", 20)]})


table = db.weechat.myrooms

print table

table.insert({"id":"xxxxxx", "rlist":[("roomtoken1", "membertoken1"), ("roomtoken2", "membertoken2"]})


table = db.weechat.roominfos


print table

table.insert({"id":"xxxxxx", "rlist":["roomtoken1", "roomtoken2"]})





http://www.snailinaturtleneck.com/blog/tag/mongodb/


'Data/Text/Knowledge Analysis & Mining > Python' 카테고리의 다른 글

OCR + python  (0) 2013.07.26
python pdf library 비교  (0) 2013.07.26
unicode, chatdet  (0) 2013.07.21
python map reduce lambda  (0) 2013.07.20
google app engine urlfetch, urllib2  (0) 2013.07.16

WRITTEN BY
manager@
Data Analysis, Text/Knowledge Mining, Python, Cloud Computing, Platform

,

python 및 머신러닝 교육, 슬로우캠퍼스



python 

웹페이지의 chatset값 구하기. http response header에 포함된 경우

import urllib2

request = "http://daum.net"

fp = urllib2.urlopen(request)

charset = fp.headers.getparam('charset')

print "***", charset

print "===\n", fp.headers



http://www.voidspace.org.uk/python/articles/urllib2.shtml#introduction




CharDet 패키지

어떤 파일이 어떠한 문자셋으로 구성되어 있는지 판단하는 기능

http://www.minvolai.com/blog/2009/11/chardet-detecting-unknown-string-encodings/


$ sudo pip install chardet


Unicode and Character Sets


http://www.joelonsoftware.com/articles/Unicode.html

'Data/Text/Knowledge Analysis & Mining > Python' 카테고리의 다른 글

python pdf library 비교  (0) 2013.07.26
mongoDB, python, twitter Oauth  (0) 2013.07.25
python map reduce lambda  (0) 2013.07.20
google app engine urlfetch, urllib2  (0) 2013.07.16
python - JSON 데이타 load 하기  (0) 2013.07.16

WRITTEN BY
manager@
Data Analysis, Text/Knowledge Mining, Python, Cloud Computing, Platform

,

python 및 머신러닝 교육, 슬로우캠퍼스


Hadoop의 map/reduce 개념도 python의 map(), reduce() 함수를 참고하지 않았을까 하는 생각을 해봅니다.


다음은 zip(), map(),  reduce(),  lambda 함수에 대한 이해를 할 수 소스 코드 입니다.


직접 입력하면서 실행해 보세요.




python - zip()


>>> a=[1,2,3]

>>> b=[4,5,6]

>>> a+b

[1, 2, 3, 4, 5, 6]

>>> zip(a,b)

[(1, 4), (2, 5), (3, 6)]


python - generator (list)

아래와 같이 [ ]를 이용하여 list를 생성하는 것이 more pythonic 한 방식이다.

>>> a

[1, 2, 3]

>>> [ x*x for x in a]

[1, 4, 9]

>>> [ x*x for x in a if x%2 == 1]

[1, 9]



일반적인  procedural language (c, java, ...) 스타일로 하면 아래와 같다.

>>> for x in a:

...     if x%2==1:

...             print x*x

...

1

9


>>> [ x+y for x,y in zip(a,b)]

[5, 7, 9]


python - map()


>>> import operator

>>> map(operator.add, a, b)

[5, 7, 9]


>>> s1= ['abb ccc', 'tttt jjjj kkk']


>>> map(str.split, s1)

[['abb', 'ccc'], ['tttt', 'jjjj', 'kkk']]


>>> [s.split()  for s in s1]

[['abb', 'ccc'], ['tttt', 'jjjj', 'kkk']]


>>> [s.split('b')  for s in s1]

[['a', '', ' ccc'], ['tttt jjjj kkk']]


python - lambda 를 이용한 간단한 함수 정의 (anonymous function)


>>> map(str.split('b'), s1)

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

TypeError: 'list' object is not callable


>>> map(lambda x: x.split('b'), s1)

[['a', '', ' ccc'], ['tttt jjjj kkk']]


>>> map(lamdba x,y: x*x+y*y , a, b)

 File "<stdin>", line 1

   map(lamdba x,y: x*x+y*y , a, b)       <--- 오타   lamdba

            ^

SyntaxError: invalid syntax


>>> map(lambda x,y: x*x+y*y , a, b)

[17, 29, 45]



>>> import math

>>> map(lambda x,y: math.sqrt(x*x+y*y) , a, b)

[4.123105625617661, 5.385164807134504, 6.708203932499369]


python - reduce()

>>> k = range(10)

>>> k

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


>>> import operator

>>> reduce(operator.add, k)

45 ---> 더하기


>>> reduce(lambda x: x*x, k)

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

TypeError: <lambda>() takes exactly 1 argument (2 given)

---> 함수 호출에서 "takes exactly n argument " 라는 오류는 함수의 인자(argument) 개수가 잘못되었을 때 발생한다.


reduce()의 첫번째 인자는 2개의 argument를 받는 함수이여야 하는데, lambda로 인자 1개 짜리 함수를 정의하여서 오류(exception) 발생한 것이다.



>>> reduce(lambda x,y: x*x, k)

0

>>> reduce(lambda x,y: y*y, k)

81

>>> reduce(lambda x,y: x+y*y, k)

285




>>> def see(x,y):

...     print x,y,'->', x+y*y

...     return x+y*y

...

>>> reduce(see, k) --> reduce() 실행 과정을 보기 위해 print

1 2 -> 5

5 3 -> 14

14 4 -> 30

30 5 -> 55

55 6 -> 91

91 7 -> 140

140 8 -> 204

204 9 -> 285

285



>>> reduce(lambda x,y: x*x+y*y, k)

160623854392948285208011982134507489923477046669785452499236264188406112786126885439804859615624545L




WRITTEN BY
manager@
Data Analysis, Text/Knowledge Mining, Python, Cloud Computing, Platform

,

python 및 머신러닝 교육, 슬로우캠퍼스


  • Google App Engine(GAE)의  urlfetch 이용하여 URL 페이지 읽어오기
  • python 기본 패키지인 urllib2 이용하여 URL 페이지 읽어오기




def get_url(word):
try:
return get_url_gae(word)
except:
return get_wiktion_xml_local(word)

def get_url_gae(word):
from google.appengine.api import urlfetch

url = 'http://abc.com/%s' % (word)
# Changing User-Agent
# https://developers.google.com/appengine/docs/python/urlfetch/#Request_Headers
# http://stackoverflow.com/questions/2743521/how-to-change-user-agent-on-google-app-engine-urlfetch-service
result = urlfetch.fetch(url=url,
headers={"User-agent", "jjjj/0.1 (2001-07-14)"}
)
if result.status_code == 200:
return result.content.decode('utf-8')
else:
return ''

def get_url_local(word):
import urllib2

url = 'http://abc.com/%s' % (word)
req = urllib2.Request(url)
req.add_header("User-agent", "jjjj/0.1 (2001-07-14)")
fp = urllib2.urlopen(req)
return fp.read().decode('utf-8')



WRITTEN BY
manager@
Data Analysis, Text/Knowledge Mining, Python, Cloud Computing, Platform

,