设为首页 加入收藏

TOP

自然语言处理3.7——用正则表达式为文本分词(二)
2017-10-09 14:22:53 】 浏览:755
Tags:自然语言 处理 3.7 正则 表达式 文本 分词
'.', 'Soup', 'does', 'very', 'well', 'without', '--', 'Maybe', "it's", 'always', 'pepper', 'that', 'makes', 'people', 'hot-tempered', ',', "'", '...']

 

NLTK的正则表达式分词器

函数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()一样。

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇关于安装ruby brew 提示失败 下一篇Ruby Web实时消息后台服务器推送..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目