函数nltk.regexp_tokenize()和re.findall()类型,但是nltk.regexp_tokenize()分词效率更高,避免了括号的特殊处理的需要。为了增加可读性,将正则表达式分为几行写,每一行添加一个解释。(?x)‘Verbose’标志告诉Python去掉嵌入的注释和空格
>>> text = 'That U.S.A. poster-print costs $12.40...'
>>> pattern = r'''(?x) # set flag to allow verbose regexps
... ([A-Z]\.)+ # abbreviations, e.g. U.S.A.
... | \w+(-\w+)* # words with optional internal hyphens
... | \$?\d+(\.\d+)?%? # currency and percentages, e.g. $12.40, 82%
... | \.\.\. # ellipsis
... | [][.,;"'?():-_`] # these are separate tokens; includes ], [
... '''
>>> nltk.regexp_tokenize(text, pattern)
['That', 'U.S.A.', 'poster-print', 'costs', '$12.40', '...']
使用verbose标志时,可以不使用' '来匹配空格字符,而是使用‘\s’代替。regexp_tokenize()有一个可选参数gaps。设置为True时,正则表达式指定标识符之间的距离。就行re.split()一样。