文本中重复的短语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')

最新更新