繁体   English   中英

与正则表达式重叠匹配 ngrams

[英]Overlapping matches with regex for ngrams

我有一个字符串,需要使用正则表达式。

"hello COMMA the matche's roll over matche's or the expression for details PCRE flavors of regex are supported here"

我想找到它的bi和trigrams。 所以专注于二元组它应该拉

hello COMMA
COMMA the
the matche's
etc

我写了这个正则表达式来做到这一点,但它没有抓住重叠的结果。

[\w'-]+ [\w'-]+

它只会抓住

hello COMMA
the matches
etc

当我把它包起来时?= 像这样它现在会抓住各种垃圾。 我错过了什么?

(?=([\w'-]+ [\w'-]+))

重叠=真实的东西也因为某种原因对我不起作用

不要使用正则表达式进行文本处理。 有专门为该工作设计的包 NLTK:

import nltk
text = "hello COMMA the matche's roll over ..."
words = nltk.word_tokenize(text)
list(nltk.bigrams(words))
# [('hello', 'COMMA'), ('COMMA', 'the'), ('the', 'matche'),...]
list(nltk.trigrams(words))
#[('hello', 'COMMA', 'the'), ('COMMA', 'the', 'matche'), ...]

请您尝试以下操作:

import re

str = "hello COMMA the matche's roll over matche's or the expression for details PCRE flavors of regex are supported here"

matches = re.finditer(r'\S+\s(?=(\S+))', str)
for match in matches:
    print(match.group(0) + match.group(1))

输出:

hello COMMA
COMMA the
the matche's
matche's roll
[snipped]

正则表达式(?=(\\S+))在正向前瞻断言中包含一个捕获组。 由于零宽度匹配,它将match.group(1)分配给匹配的子字符串而不向前移动位置。

下面的正则表达式是对@Wiktor 对该问题的评论中建议的正则表达式的概括和简化。 Wiktor 的解决方案是 2-grams(或 bigrams)。 此解决方案适用于 3-gram(或 trigram)。 对于 n-gram,其中n是一个变量,将{2}替换为{#{n-1}}

首先假设字符串只包含单词字符和空格。 然后可以使用以下正则表达式来提取三元组:

(?=(?<!\S)(\w+(?:\s+\w+){2}))

例子

正则表达式可以分解如下:

(?=           # begin a positive lookahead   
  (?<!        # begin a negative lookbehind
    \S        # match a a non-whitespace char
  )           # end the negative lookbehind
  (           # begin capture group 1
    \w+       # match 1+ word chars
    (?:       # begin a non-capture group
      \s+\w+  # match 1+ whitespace chars followed by 1+ word chars
    )         # end non-capture group
    {1,2}     # execute the non-capture group 1-2 times 
  )           # end capture group
)             # end positive lookahead

如果,如在示例中,字符串也可能包含单词内的撇号(但不在单词的开头或结尾),则上面的每个标记\\w+都可以替换为\\w+(?:[']\\w+)*以获得:

(?=(?<!\S)((?:\w+(?:[']\w+)*(?:\s+\w+(?:[']\w+)*){1,2})))

例子

但是,如果对某些字符的可能数字和位置要求太多,则正则表达式很快就会崩溃。

这是其中一个正则表达式应该被使用,因为所期望的阵列可更容易地与其他工具来制造的情况下的例子。 然而,这是一个有用的练习,因为它确实提高了使用正则表达式的能力。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM