【发布时间】:2014-04-06 05:20:15
【问题描述】:
我正在尝试编写一个文本规范器,需要处理的基本情况之一是将3.14 转换为three point one four 或three 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
这是我的一些测试字符串:
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']
【问题讨论】:
-
?是非贪婪的(最小匹配)尝试用 {,1} 替换它
-
试试这个:
(\$?\d+(?:\.\d+)?%?) -
你能提供你用来测试这个的代码吗?我无法在这里重现该问题,23.50 美元和 3.14 美元都处理得很好
-
@gonz,我已经编辑了问题。
标签: python regex nltk tokenize