NLTK正则表达式标记器在正则表达式中与小数点不一致

Jes*_*ang 5 python regex tokenize nltk

我想写一个文本规范化,以及需要处理的基本情况之一是转像3.14three point one fourthree point fourteen.

我目前使用的模式\$?\d+(\.\d+)?%?nltk.regexp_tokenize,我认为应该处理数以及货币和百分比.但是,目前,类似的东西$23.50被完美处理(它解析['$23.50']),但3.14正在解析['3', '14']- 小数点被删除.

我已经尝试\d+.\d+在我的正则表达式中添加一个单独的模式,但这没有帮助(并且我的当前模式不应该已经匹配了吗?)

编辑2:我也刚刚发现该%部件似乎也没有正常工作 - 20%只返回['20'].我觉得我的正则表达式肯定有问题,但我已经在Pythex中测试了它看起来很好吗?

编辑:这是我的代码.

import nltk
import re

pattern = r'''(?x)    # set flag to allow verbose regexps
            ([A-Z]\.)+        # abbreviations, e.g. U.S.A.
            | \w+([-']\w+)*        # words w/ optional internal hyphens/apostrophe
            | \$?\d+(\.\d+)?%?  # numbers, incl. currency and percentages
            | [+/\-@&*]         # special characters with meanings
            '''
    words = nltk.regexp_tokenize(line, pattern)
    words = [string.lower(w) for w in words]
    print words
Run Code Online (Sandbox Code Playgroud)

以下是我的一些测试字符串:

32188
2598473
26 letters from A to Z
3.14 is pi.                         <-- ['3', '14', 'is', 'pi']
My weight is about 68 kg, +/- 10 grams.
Good muffins cost $3.88 in New York <-- ['good', 'muffins', 'cost', '$3.88', 'in', 'new', 'york']
Run Code Online (Sandbox Code Playgroud)

Jer*_*rry 7

罪魁祸首是:

\w+([-']\w+)*
Run Code Online (Sandbox Code Playgroud)

\w+将匹配数量和因为没有.在那里,它将匹配33.14.将选项移动一点,使其\$?\d+(\.\d+)?%?位于上述正则表达式部分之前(以便首先尝试匹配数字格式):

(?x)([A-Z]\.)+|\$?\d+(\.\d+)?%?|\w+([-']\w+)*|[+/\-@&*]
Run Code Online (Sandbox Code Playgroud)

regex101演示

或者以扩展形式:

pattern = r'''(?x)               # set flag to allow verbose regexps
              ([A-Z]\.)+         # abbreviations, e.g. U.S.A.
              | \$?\d+(\.\d+)?%? # numbers, incl. currency and percentages
              | \w+([-']\w+)*    # words w/ optional internal hyphens/apostrophe
              | [+/\-@&*]        # special characters with meanings
            '''
Run Code Online (Sandbox Code Playgroud)

  • @JessicaYang`\b`在'%`和空格之间不匹配,因为它们都是非单词字符.尝试将其用于数字部分:`\ $?\ d +\b(\.\ d +)?%?`它将解决您当前遇到的问题,但我不知道它是否会解决未来问题.也许你需要一个不同的方法= / (2认同)