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

2024-05-29 04:52:28 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我想使用python和提取文本,要么是一个数字值,要么是一个数字拼写加上第一个字前后找到的值。你知道吗

示例文本:

I have 2 brothers and they bought one car each. My oldest brother invested 1,000 dollars.

预期产量:

'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。我也不知道用什么来得到单词前后找到的单词。你知道吗


Tags: and文本myhave数字caroneeach
2条回答

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

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

产生你想要的输出。当然,它只能找到英文拼写的一位数。对于任意数字,需要使用适当的解析器。但这可能就够你想做的了。你知道吗

假设数字的文本形式从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))

相关问题 更多 >

    热门问题