簡體   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