[Python]テクニカルで使う英単語を収集する。

技術的な英単語を収集して効率的に覚えようかなーと思ったので、適当に書いた。

サードパーティライブラリとしてBeautifulSoupを使ってるよ。

クローラ化するのは怖いからやめといた。

# -*- coding: utf-8 -*-                                                                                                                                      
import re, urllib2

try:
    from BeautifulSoup import BeautifulSoup, Comment
except ImportError, e:
    raise e

URL = ''
IGNORE_PATTERN = [
    ('\r', ' '),
    ('\n', ' '),
    ('\t', ' '),
    ('\.', ' '),
    (',', ' '),
    (':', ' '),
    ('\|', ' '),
    ('\(', ' '),
    ('\)', ' '),
    ('{%', ' '),
    ('%}', ' '),
    ('--', ' '),
    ('[0-9]', ' '),
   ]

def main():
    # htmlの取得                                                                                                                                             
    opener = urllib2.urlopen(URL)
    html = opener.read()

    soup = BeautifulSoup(html)

    # コメントを除去する                                                                                                                                     
    # <!-- -->                                                                                                                                               
    comments = soup.findAll(text=lambda text:isinstance(text, Comment))
    [comment.extract() for comment in comments]

    body = get_body(soup)
    text = get_text_only(body)

    for old, new in IGNORE_PATTERN:
        #text = text.replace(old, new)                                                                                                                       
        try:
            text = re.sub(old, new, text)
        except Exception, e:
            raise Exception(old)

    # 半角スペースを取り除く                                                                                                                                 
    words = [word.lower() for word in text.split(' ') if not word == u'']
    #words = set([word.lower() for word in text.split(' ') if not word == u''])

    print(words)
    print(u'word: %s' % len(words))


def get_body(soup):
    return soup.body

def get_text_only(soup):
    v = soup.string
    if v == None:
	c = soup.contents
        result_text = ''
        for t in c:
            sub_text = get_text_only(t)
            #print(sub_text)                                                                                                                                 
            result_text += sub_text + ' '
        return result_text
    else:
        return v.strip()


if __name__ == '__main__':
    main()

注意点として、get_text_onlyはOreillyから出版された書籍「集合知プログラミング」を参考にしてる。

タスク

  • 晒す予定ないけどクローラ化する。逮捕注意。
  • DBにぶっこむ。