Python提取可量化文本(数字)

时间:2018-05-03 02:10:36

标签: python regex nlp

您好我想使用python并提取文本,该文本是数字值或拼写的数字加上找到的值之前和之后的第一个单词。

示例文字:

  我有2个兄弟,他们分别买了一辆车。我最老的   兄弟投资了1000美元。

预期产出:

'have 2 brothers', 'bought one car', 'invested 1,000 dollars'

我试过这个>

>>> import re
>>> str = "I have 2 brothers and they bought one car each. My oldest brother invested 1,000 dollars."
>>> print re.findall("\d+", s)
['2']

然而,这仅适用于查找不是拼写出的术语one的值。我也不知道在找到的单词之前和之后用什么来获取单词。

2 个答案:

答案 0 :(得分:1)

这个快速而又脏的正则表达式:

pat = re.compile(r'(\w+\s+)([\d,]+|one|two|three|four|five|six|seven|eight|nine)(\s+\w+)')

确实产生了你想要的输出。当然,它只能找到用英语拼写的单位数字。对于任意数字,您需要使用适当的解析器。但它可能就足以满足您的目标。

答案 1 :(得分:0)

假设数字的文本形式只从1到10。

import re

text = 'I have 2 brothers and they bought one car each. My oldest brother invested 1,000 dollars.'
text_numbers = []
numbers = re.findall(r'[0-9,\-]+|one|two|three|four|five|six|seven|eight|nine|ten', text)
for number in numbers:
    parts = text.split(number)
    first_part = parts[0].strip().split(' ')[-1]
    second_part = parts[1].strip().split(' ')[0]
    print('{} {} {}'.format(first_part, number, second_part))