首页 > 解决方案 > 正则表达式匹配单点但不匹配数字或沉默

问题描述

我正在为教程开发一个句子和标记器。这意味着将文档字符串拆分为句子,将句子拆分为单词。例子:

#Sentencizing
"This is a sentence. This is another sentence! A third..."=>["This is a sentence.", "This is another sentence!", "A third..."]
#Tokenizatiion
"Tokens are 'individual' bits of a sentence."=>["Tokens", "are", "'individual'", "bits", "of", "a", "sentence", "."]

正如所见,需要的不仅仅是 string.split()。我正在使用 re.sub() 为每个匹配附加一个“特殊”标签(然后在这个标签中拆分),首先是句子,然后是标记。

到目前为止它工作得很好,但是有一个问题:如何制作一个可以在点处分割但不能在 (...) 或数字 (3.14) 处分割的正则表达式?

我一直在使用这些选项与前瞻(我需要匹配组,然后能够召回它进行追加),但没有一个工作:

#Do a negative look behind for preceding numbers or dots, central capture group is a dot, do the same as first for a look ahead.
(?![\d\.])(\.)(?<![\d\.])

该应用程序是:

sentence = re.sub(pattern, '\g<0>'+special_tag, raw_sentence)

标签: pythonregex

解决方案


我使用以下内容来查找看起来相关的时期:

import re
m = re.compile(r'[0-9]\.[^0-9.]|[^0-9]\.[^0-9.]|[!?]')
st = "This is a sentence. This is another sentence! A third...  Pi is 3.14.  This is 1984.  Hello?"
m.findall(st)

# if you want to use lookahead, you can use something like this:
m = re.compile(r'(?<=[0-9])\.(?=[^0-9.])|(?<=[^0-9])\.(?=[^0-9.])|[!?]')

它不是特别优雅,但我也尝试处理“我们有 0.1% 的成功机会”的情况。

祝你好运!


推荐阅读