【问题标题】:Modify NLTK word_tokenize to prevent tokenization of parenthesis修改 NLTK word_tokenize 防止括号分词
【发布时间】:2016-09-03 16:02:33
【问题描述】:

我有以下main.py

#!/usr/bin/env python
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:

import nltk
import string
import sys
for token in nltk.word_tokenize(''.join(sys.stdin.readlines())):
    #print token
    if len(token) == 1 and not token in string.punctuation or len(token) > 1:
        print token

输出如下。

./main.py <<< 'EGR1(-/-) mouse embryonic fibroblasts'
EGR1
-/-
mouse
embryonic
fibroblasts

我想稍微更改标记器,以便它将EGR1(-/-) 识别为一个标记(无需任何其他更改)。有谁知道是否有一种方法可以稍微修改标记器?谢谢。

【问题讨论】:

    标签: python regex nlp nltk tokenize


    【解决方案1】:

    NLTK 中的默认 word_tokenize() 函数是 TreebankWordTokenizer,它基于一系列正则表达式替换。

    更具体地说,在括号之间添加空格时,TreebankWordTokenizer 使用此正则表达式替换:

    PARENS_BRACKETS = [
        (re.compile(r'[\]\[\(\)\{\}\<\>]'), r' \g<0> '),
        (re.compile(r'--'), r' -- '),
    ]
    
    for regexp, substitution in self.PARENS_BRACKETS:
        text = regexp.sub(substitution, text)
    

    例如:

    import re
    
    text = 'EGR1(-/-) mouse embryonic fibroblasts'
    
    PARENS_BRACKETS = [
        (re.compile(r'[\]\[\(\)\{\}\<\>]'), r' \g<0> '),
        (re.compile(r'--'), r' -- '),
    ]
    
    for regexp, substitution in PARENS_BRACKETS:
        text = regexp.sub(substitution, text)
    
    print text
    

    [出]:

    EGR1 ( -/- )  mouse embryonic fibroblasts
    

    所以回到“破解”NLTK word_tokenize() 函数,您可以尝试这样的方法来取消 PARENS_BRACKETS 替换的效果:

    >>> from nltk.tokenize import TreebankWordTokenizer
    >>> tokenizer = TreebankWordTokenizer()
    >>> tokenizer.PARENS_BRACKETS = []
    >>> text = 'EGR1(-/-) mouse embryonic fibroblasts'
    >>> tokenizer.tokenize(text)
    ['EGR1(-/-)', 'mouse', 'embryonic', 'fibroblasts']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 2016-05-22
      相关资源
      最近更新 更多