繁体   English   中英

使用正则表达式从单元格中搜索多个关键词

[英]using regular expression for searching multiple key words from cells

我必须编写一个代码,用于从将句子组合在一起的 Excel 表中搜索正则表达式。 我已经设法找到代表每个句子的关键词。 当我运行下面提到的代码时,它只从一个单元格中找到一个关键字并移动到下一个单元格。 我试图在表格中显示要求

在此处输入图片说明

\bphrase\W+(?:\w+\W+){0,6}?one\b|\bphrase\W+(?:\w+\W+){0,6}?two\b|\bphrase\W+(?:\w+\W+){0,6}?three\b|\bphrase\W+(?:\w+\W+){0,6}?four\b|

正则表达式:

\b(phrase)\b\W+(?:\w+\W+){0,6}?\b(one|two|three|four)\b
  1. \\b(phrase)\\b匹配单词边界上的phrase
  2. W+ :匹配一个或多个非单词字符(通常是空格)。
  3. (?:\\w+\\W+){0,6}? 匹配 0 到 6 次,尽可能少,一个或多个单词字符后跟一个或多个非单词字符。
  4. \\b(one|two|three|four)\\b匹配单词边界上的onetwothreefour

编码:

import re

text = "This sentence has phrase one and phrase word word two and phrase word three and phrase four phrase too many words too many words too many words four again."

l = [m[1] + ' ' + m[2] for m in re.finditer(r'\b(phrase)\b\W+(?:\w+\W+){0,6}?\b(one|two|three|four)\b', text)]
print(l)

印刷:

['phrase one', 'phrase two', 'phrase three', 'phrase four']

暂无
暂无

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

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