繁体   English   中英

文字Python中的重复短语_跟进

[英]Repeated Phrases in text Python _ Follow up

另一个用户已经开始讨论如何在Python中查找重复的短语,但仅关注三个单词的短语。

Robert Rossney的答案是完整且有效的(这是Python文本中的重复短语 ),但是我能要求一种简单地找到重复短语的方法吗,尽管它们的长度如何? 我认为可以详细说明上一次讨论中已经阐述的方法,但是我不确定如何做到这一点。

我认为这可能是为了返回不同长度的元组而可以修改的函数:

def phrases(words):
    phrase = []
    for word in words:
        phrase.append(word)
        if len(phrase) > 3:
            phrase.remove(phrase[0])
        if len(phrase) == 3:
            yield tuple(phrase)

一种简单的修改是将字长传递给phrases方法,然后以不同的字长调用该方法。

def phrases(words, wlen):
  phrase = []
  for word in words:
    phrase.append(word)
    if len(phrase) > wlen:
        phrase.remove(phrase[0])
    if len(phrase) == wlen:
        yield tuple(phrase)

然后将all_phrases定义为

def all_phrases(words):
   for l in range(1, len(words)):
      yield phrases(words, l)

然后使用它的一种方法是

for w in all_phrases(words):
   for g in w:
     print g

对于words = ['oer', 'the', 'bright', 'blue', 'sea'] ,它产生:

('oer',)
('the',)
('bright',)
('blue',)
('sea',)
('oer', 'the')
('the', 'bright')
('bright', 'blue')
('blue', 'sea')
('oer', 'the', 'bright')
('the', 'bright', 'blue')
('bright', 'blue', 'sea')
('oer', 'the', 'bright', 'blue')
('the', 'bright', 'blue', 'sea')

暂无
暂无

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

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