python - 正则表达式匹配单点但不匹配数字或沉默
问题描述
我正在为教程开发一个句子和标记器。这意味着将文档字符串拆分为句子,将句子拆分为单词。例子:
#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)
解决方案
我使用以下内容来查找看起来相关的时期:
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% 的成功机会”的情况。
祝你好运!
推荐阅读
- compiler-errors - mpifort -DMPI 编译错误:派生类型“mpi_status”用作实际参数。适用于英特尔 Fortran,但不适用于 GNU Fortran
- javascript - 即使垂直滚动条位于顶部,如何使水平滚动条始终可见
- javascript - 位置 div 之间的空间:相对
- javascript - 嵌套对象数组的 Javascript 解决方法
- c++ - 如何使用 C++ 在 OpenCV 4.2.0 中使用 SIFT?
- java - Java:glScissor 多边形
- pyspark - 如何从pyspark中的xml读取嵌套元素?
- sequelize.js - 查找嵌套包含匹配所有内容的行
- javascript - 调用大于 x 长度的单词的方法
- python-3.x - 获取其中元素的直接容器?