17
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

日本語以外の文字と記号を排除し日本語の平文コーパスを作成する呪文

Last updated at Posted at 2015-10-20

日本語の自然言語ライブラリの中には、ヘブライ語や韓国語をぶちこんだ瞬間にエラーで処理が止まるライブラリ多いです。そんなときに便利な呪文を紹介します。

たとえばPyCon2015で紹介されたのjanomeは韓国語が混入するとエラーで死ぬ

janomeはMeCabをインストールする手間を省いてくれる素晴らしい形態素解析器なのですが、日本語以外の文字が1文字でも混入するとエラーで死にます。wikipediaの左言語切り換えバーを読み込んだ例だと...

wikipediaの左のバーより
text = "他言語版Italiano한국어PolskiSimple English"
t = Tokenizer()
for token in t.tokenize(text):
     print token

---------------
Traceback (most recent call last):
  File "tests.py", line 98, in <module>
    for token in t.tokenize(text):
  File "lib/python2.7/site-packages/janome/tokenizer.py", line 107, in tokenize
    pos += lattice.forward()
  File "lib/python2.7/site-packages/janome/lattice.py", line 124, in forward
    while not self.enodes[self.p]:
IndexError: list index out of range

そんなときはこの呪文

import re
import nltk

def filter(text):
   """
   :param text: str
   :rtype : str
   """
   # アルファベットと半角英数と記号と改行とタブを排除
   text = re.sub(r'[a-zA-Z0-9¥"¥.¥,¥@]+', '', text)
   text = re.sub(r'[!"“#$%&()\*\+\-\.,\/:;<=>?@\[\\\]^_`{|}~]', '', text)
   text = re.sub(r'[\n|\r|\t]', '', text)

   # 日本語以外の文字を排除(韓国語とか中国語とかヘブライ語とか)
   jp_chartype_tokenizer = nltk.RegexpTokenizer(u'([ぁ-んー]+|[ァ-ンー]+|[\u4e00-\u9FFF]+|[ぁ-んァ-ンー\u4e00-\u9FFF]+)')
   text = "".join(jp_chartype_tokenizer.tokenize(text))
   return text


text = "他言語版Italiano한국어PolskiSimple English"
text = filter(text)
t = Tokenizer()
for token in t.tokenize(text):
     print token


------------------
	接頭詞,名詞接続,*,*,*,*,,,
言語	名詞,一般,*,*,*,*,言語,ゲンゴ,ゲンゴ
	名詞,接尾,一般,*,*,*,,バン,バン
17
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?