【问题标题】:Repeated Phrases in text Python _ Follow up文本 Python 中的重复短语 _ 跟进
【发布时间】:2014-03-11 21:51:45
【问题描述】:

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

Robert Rossney 的答案是完整且有效的(这里是repeated phrases in the text 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)

【问题讨论】:

    标签: python phrases


    【解决方案1】:

    一个简单的修改是将字长传递给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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多