例:在下面的课文中,我有
你在室外留下的沙坑与你在室外留下的沙坑有不同的外观,和你在室外留下的弹坑有不同的外观。
月球和太空中的其他物体帮助科学家理解重力是如何工作的。..。
空间探索如何帮助我们更多地了解地球空间探索如何帮助我们更多地了解地球太空探索帮助我们更多地了解地球太空探索帮助我们更多地了解地球空间探索帮助我们了解更多地球。
我只想捕捉每个重复的单词模式中的一次:
你在室外留下的沙坑与月球和太空中的其他物体的外观不同,这有助于科学家了解重力是如何工作的。太空探索是如何帮助我们更多地了解地球的?
注:文字都在一行,所以看上去更像
你在室外留下的沙坑与你留在室外的沙坑的外观不同,你留在室外的弹坑和你留在室外的弹坑不同,月球和太空中的其他物体帮助科学家理解重力是如何工作的。空间探索如何帮助我们更多地了解地球空间探索如何帮助我们更多地了解地球太空探索帮助我们更多地了解地球太空探索帮助我们更多地了解地球空间探索帮助我们了解更多地球。
发布于 2014-07-03 07:46:23
在你的样本中,重复的短语总是紧跟在原语之后,我们能指望吗?此外,您是否可以使用regex风格/工具/语言而不是awk或sed?如果这两个问题的答案都是肯定的,那么一个纯粹的regex解决方案可能是可能的。这应该适用于大多数Perl派生的版本(PHP、.NET、Perl等):
\b(\w+(?:\W+\w+)+?)\W+(?=\1\b)我在这里做了大量的简化假设,这样我就可以专注于这项技术了。单词被定义为一组单词字符,由一个或多个非单词字符(例如空格和标点符号)与相邻的单词分隔。
第一部分-- \b(\w+(?:\W+\w+)+?) --匹配至少两个单词长的“短语”,在第一组中捕捉它;第二部分-- \W+(?=\1\b) --试图再次匹配相同的短语,但不消耗它。如果匹配成功,我们将其替换为空字符串,有效地删除第一个短语以及引入第二个短语的\W+,而不是第二个短语本身。
请注意,第二个短语必须与第一个短语完全相同,包括大写和单词之间空格的数目和种类。换句话说,这是一个非常脆弱的解决方案。我强烈建议您继续研究NLP方法。Regexes强迫您始终处理语法,而此时您应该在语义级别上工作。(这是我们敦促人们不要在HTML上使用regexes的主要原因之一。)
发布于 2014-07-03 02:41:10
蛮力:
s = 'craters in the sand that you left outdoors differ in appearance from the craters in the sand that you left outdoors differ in appearance from the craters in the sand that you left outdoors differ in appearance from the Moon and other bodies in space helped scientists understand how gravity works. How space exploration has helped us to learn more about Earth How space exploration has helped us to learn more about Earth How space exploration has helped us to learn more about Earth How space exploration has helped us to learn more about Earth How space exploration has helped us to learn more about Earth'
ss = [s[i:] for i in xrange(len(s))]
ss = sorted(ss)
all_matches = []
for i in xrange(len(ss)-1):
a = ss[i]
b = ss[i+1]
cap = min(len(a), len(b))
for j in xrange(cap):
if a[j] <> b[j]:
if j > 0:
all_matches.append(a[:j])
break
elif j+1 == cap:
all_matches.append(a[:j+1])
def match_exist(matches, m):
for m2 in matches:
if m in m2:
return True
return False
matches = []
all_matches.sort(key=len, reverse=True)
for m in all_matches:
if not match_exist(matches, m):
matches.append(m)
for m in matches:
print m产出:
How space exploration has helped us to learn more about Earth How space exploration has helped us to learn more about Earth How space exploration has helped us to learn more about Earth How space exploration has helped us to learn more about Earth
craters in the sand that you left outdoors differ in appearance from the craters in the sand that you left outdoors differ in appearance from the
ie
st如果不需要重叠匹配,则只需使用regex反向引用:
(\b.+\b)\1演示
https://stackoverflow.com/questions/24543853
复制相似问题