Python: 滑动窗口比较列表中的词与给定词典中的词

-2 投票
1 回答
669 浏览
提问于 2025-04-18 12:50

我想用滑动窗口的方法来检查“文档”中的单词是否和“词典”中的单词匹配。我想问的是:哪个主要的函数可以做到这一点?我看到了一些滑动窗口的例子,但似乎都不是我想要的。

document=['hello','my','world','love'], lexicon=['questions','hello','shift',.....]

如果我设置滑动窗口的大小为3,那是不是意味着我会得到

('hello','my','world') and ('my','world','love')

对于每一个,我想测试一下

'hello','my','world' 

是否在词典中,然后再测试一下

'hello my','my world', 'hello world' 

是否在词典中,并且测试一下

'hello my world'

是否在词典中。

1 个回答

0
import itertools 

document=['hello','my','world','love']

for x in range(len(document)-2):
    words = document[x:x+3]
    print 'words:', words

    print "--- 1 ---"
    for y in itertools.combinations(words,1):
        print ' '.join(y)

    print "--- 2 ---"
    for y in itertools.combinations(words,2):
        print ' '.join(y)

    print "--- 3 ---"
    print ' '.join(words)

    print "-----------------"

结果

words: ['hello', 'my', 'world']
--- 1 ---
hello
my
world
--- 2 ---
hello my
hello world
my world
--- 3 ---
hello my world
-----------------
words: ['my', 'world', 'love']
--- 1 ---
my
world
love
--- 2 ---
my world
my love
world love
--- 3 ---
my world love
-----------------

撰写回答