首页 > 解决方案 > 通过shell终端仅使用正则表达式仅提取(从文本中)非重复单词

问题描述

我只想提取在下面的文本中不重复的单词。我只想使用正则表达式,并且我看到了一些类似的问题,如Only extract those words from a list that include no repeating letters, using regex (don't repeat letters) and Regular Expression :match string contains only non repeating words。我希望结果是一个不重复出现在文本中的自然顺序的单词列表。

我的通用格式文本:

教学心理学是教育心理学的一部分,指的是学校教育。正如稍后将看到的,两者都有相同的目标:研究、解释和理解由于人们参与活动而产生的行为变化过程。在行为改变研究的基础上存在的教育活动的特征。

使用这个问题的答案,我在垂直列表中逐字逐句的文本(如果这样使用更容易的话)

标签: regexwordnon-repetitive

解决方案


如果您需要纯正则表达式解决方案,则只能使用 .NET 或 Python PyPi 正则表达式来实现,因为您需要正则表达式库通常不具备的两件事:1)从右到左的输入字符串解析和 2)无限宽度的后视。

这是一个 Python 解决方案:

import regex
text="Teaching psychology is the part of educational psychology that refers to school education. As will be seen later, both have the same objective: to study, explain and understand the processes of behavioral change that are produce in people as a consequence of their participation in activities educational What gives an entity proper to teaching psychology is the nature and the characteristics of the educational activities that exist at the base of the of behavioral change studied."
rx = r'(?rus)(?<!\b\1\b.*?)\b(\w+)\b'
print (list(reversed(regex.findall(rx, text))))

查看在线演示

细节

  • (?rus)-r启用从右到左的输入字符串解析(正则表达式中的所有模式像往常一样从左到右匹配,因此匹配文本不会反转),u在 Python 2 中用于使\wUnicode 感知,它是 Python 中的默认选项3、s是DOTALL修饰符使.匹配换行符
  • (?<!\b\1\b.*?)- 如果紧邻当前位置的左侧,则不匹配,有任何 0+ 个字符,然后与第 1 组中捕获的相同文本(见表达式后面)作为整个单词
  • \b(\w+)\b- 一个完整的单词,单词边界内的 1+ 个单词字符。

用于以原始顺序打印单词,因为从右到左的reversed正则表达式从头到尾匹配它们。


推荐阅读