问题描述
以下是我的句子:例如:
这是第一个:示例 234 -
这是第二个(示例)345 1
这是我的第三个例子 (456) 3
预期输出:
['this is first: example', 234, -]
['this is second (example)', 345, 1]
['this is my third example', (456), 3]
我厌倦了使用 python、nltk 单词标记和句子标记、split() 和
str1 = re.compile('([\\w: ]+)|([0-9])') str1.findall('my above examples')
请建议我一个可以提供我预期输出的模块,或者让我知道我在正则表达式中的错误
1楼
使用您的表达式,由于交替,您将获得单独的匹配项。 如果您可以在一行中期望三个部分的组,只需创建一个匹配整行的表达式并分别捕获三个组。 例如。
^(.*) ([\d()]+) ([-\d])
请注意,这是有效的,因为当.*
匹配整行时,引擎会回溯并放弃字符以匹配末尾的数字组。
在代码中:
regex = r"^(.*) ([\d()]+) ([-\d])"
matches = re.findall(regex, your_text, re.MULTILINE)
print(matches)
输出:
[('this is first: example', '234', '-'),
('this is second (example)', '345', '1'),
('this is my third example', '(456)', '3')]
编辑
如果您知道最后需要多少组数字,则上述模式效果很好。
但是,如果该数字是可变的,则您需要创建静态数量的重复可选数字组,例如(?:\\d+)?
预计您必须匹配的值的数量,但这很麻烦,并且可能仍然无法满足弹出的所有要求。
因此,在一个块中捕获源中出现的所有数字并在之后将其拆分将是更好的选择。 为此,我们将字符串的开头与一个惰性量词匹配,以允许匹配字符串末尾的所有可用数字组,我们将在一个中捕获这些数字组。 例如:
^(.*?)((?: [-\d()]+)+)$
请参阅。
然后我们可以将捕获的一组数字拆分为一个数组,我们将其包含在描述中。 示例代码:
import re
test_str = (
"this is first: example 234 -\n"
"this is second (example) 345 1\n"
"this is my third example (456) 3\n"
"this is the fourth example (456) 4 12\n"
"this is the fifth example 300 1 16 200 (2) 18")
regex = r"^(.*?)((?: [-\d()]+)+)$"
matches = re.findall(regex, test_str, re.MULTILINE)
captures = [(a, b.split()) for (a, b) in matches]
print(captures)
输出:
[
('this is first: example', ['234', '-']),
('this is second (example)', ['345', '1']),
('this is my third example', ['(456)', '3']),
('this is the fourth example', ['(456)', '4', '12']),
('this is the fifth example', ['300', '1', '16', '200', '(2)', '18'])
]