【问题标题】:Python Sliding Window on sentence string句子字符串上的Python滑动窗口
【发布时间】:2017-08-08 03:31:56
【问题描述】:

我正在寻找一个由窗口大小为 N 的单词组成的字符串的滑动窗口拆分器。

输入:“我爱吃,我爱喝”,窗口大小 3

输出:[“我喜欢食物”、“喜欢食物和”、“食物和我”、“我喜欢”.....]

所有关于窗口滑动的建议都是围绕字符串序列,没有术语。有什么开箱即用的东西吗?

【问题讨论】:

  • 这是我最终所做的:def find_ngrams(input_list, n): return zip(*[input_list[i:] for i in range(n)])

标签: python string python-2.7 sliding-window


【解决方案1】:

您可以使用具有不同偏移量的迭代器并将它们全部压缩。

>>> arr = "I love food. blah blah".split()
>>> its = [iter(arr), iter(arr[1:]), iter(arr[2:])] #Construct the pattern for longer windowss
>>> zip(*its)
[('I', 'love', 'food.'), ('love', 'food.', 'blah'), ('food.', 'blah', 'blah')]

如果您的句子很长,或者可能是普通的旧循环(如在其他答案中),您可能想要使用 izip

【讨论】:

    【解决方案2】:

    一种基于下标字符串序列的方法:

    def split_on_window(sequence="I love food and I like drink", limit=4):
        results = []
        split_sequence = sequence.split()
        iteration_length = len(split_sequence) - (limit - 1)
        max_window_indicies = range(iteration_length)
        for index in max_window_indicies:
            results.append(split_sequence[index:index + limit])
        return results
    

    样本输出:

    >>> split_on_window("I love food and I like drink", 3)
    ['I', 'love', 'food']
    ['love', 'food', 'and']
    ['food', 'and', 'I']
    ['and', 'I', 'like']
    ['I', 'like', 'drink']
    

    这是受@SuperSaiyan 启发的另一个答案:

    from itertools import izip
    
    def split_on_window(sequence, limit):
        split_sequence = sequence.split()
        iterators = [iter(split_sequence[index:]) for index in range(limit)]
        return izip(*iterators)
    

    样本输出:

    >>> list(split_on_window(s, 4))
    [('I', 'love', 'food', 'and'), ('love', 'food', 'and', 'I'), 
    ('food', 'and', 'I', 'like'), ('and', 'I', 'like', 'drink')]
    

    基准测试:

    Sequence = I love food and I like drink, limit = 3
    Repetitions = 1000000
    Using subscripting -> 3.8326420784
    Using izip -> 5.41380286217 # Modified to return a list for the benchmark.
    

    【讨论】:

      【解决方案3】:
      def token_sliding_window(str, size):
          tokens = str.split(' ')
          for i in range(len(tokens )- size + 1):
              yield tokens[i: i+size]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-06
        • 2019-10-28
        • 2017-11-04
        • 2011-11-29
        • 2023-03-25
        相关资源
        最近更新 更多