2008-02-28 22:36:13
昨日は一行一文に整形された文書を各行一つの検索語のみ表示させてみたが、今日は文書ファイルを全部読み込んで、検索語を次々に拾って、前後を切り取って表示させていくようにしてみた。
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import sys
import re
word = sys.argv[1]
file = sys.argv[2]
input = open(file,'r').read()
txt = re.sub('\x0D\x0A|\x0A|\x0D', '\n', input)
txt = re.sub('(\n)+', ' ', txt)
txt = re.sub('\t', ' ', txt)
txt = re.sub('<.+?>', ' ', txt)
blocks = txt.split(word)
i = 0
for block in blocks:
  if i > 1:
    left = prev[-20:]
    right = block[0:20]
    print left.rjust(20) + word + right
  prev = block
  i = i + 1
 html文書のタグを取り除くようにしている。改行コードはこれではうまく変換されていないが、どうしたらいいのか、よく判らない。PHPのときにはこれでできていた。
$ python kwic2.py string test.txt
  s in Python: byte strings and Unicode 
      s and Unicode strings. As you may have g
ave guessed, a byte string is a sequence of by
This creates a byte string: byteString = "hell
s creates a Unicode string: unicodeString = u"
ld!" Convert a byte string into a Unicode 
     into a Unicode string and back again: s =
 こんな具合になる。Pythonってi++は使えないのかな。何もかもまだよく判らない。まだ語頭が大文字だと逃してしまったりする。