搜索包含6个单词的字符串作为真实单词

时间:2012-02-24 06:52:50

标签: python

我正在导入一个“字典”文件,其中包含我作为数组读入的单词。然后,我想要搜索由排列函数为这些单词中的每一个单词生成的6个单词短语,并且如果从词典数组中找到与短语中的任何单词匹配的匹配则打印出来。如果我能打印出来,只有找到匹配的整个短语才更合适。置换的输出产生由空格分隔的6个字符串。

由于

import itertools
import array
arr=[]
f = file('/home/kyle/dictionary.csv').readlines()
for i in range(len(f)):
    arr.append(f[i].rstrip('\n').rstrip('\r').split(','))

for a in range(0, len(arr)):
    print arr[a]

s=['e','k','y','a','v','y','a','a','o','s','r','h','t','n','i','k','h','t','s','t','e','n','i','p','p','l','e','h','d','c','t','e','f','a','t','t','l']
for L in range(1, len(s)+1):
for subset in itertools.permutations(s, 37):
    x=( "".join(subset))
    s=x[:5] + ' ' + x[5:]
    s=s[:16] + ' ' + s[16:]
    s=s[:20] + ' ' + s[20:]
    s=s[:27] + ' ' + s[27:]
    s=s[:31] + ' ' + s[31:]
    s=s[:35] + ' ' + s[35:]
    for c in range(0,len(arr)):

        test=str(arr[c])
        if test in s:
            print s

底部正在玩“in”以找到可能的匹配,但似乎没有结果。代码非常混乱

2 个答案:

答案 0 :(得分:1)

希望这会有所帮助,这是一个非常天真的实现,但作为一个起点可能是有用的。

In [2]: words = ['word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7']

In [3]: phrase1 = 'bla bla word1 bla word2 bla word7'

In [4]: phrase2 = 'bla bla word1 bla word2 bla word7 word6, word4 word3'

In [5]: def match(phrase):
   ...:     n_matches = 0
   ...:     for w in words:
   ...:         if w in phrase:
   ...:             n_matches += 1
   ...:     return n_matches == 6
   ...: 

In [6]: match(phrase1)
Out[6]: False

In [7]: match(phrase2)
Out[7]: True

问题在于我们找到了子串:

In [8]: phrase3 = 'bla bla word1 bla word2 bla word7 word6, word4 word3failed'

In [9]: match(phrase3)
Out[9]: True

我这样解决了:

In [22]: import re
In [25]: tokenize_words = re.compile(r'\w+')
In [30]: def match(phrase):
   ....:     n_matches = 0
   ....:     phrase_words = tokenize_words.findall(phrase)
   ....:     for w in words:
   ....:         if w in phrase_words:
   ....:             n_matches += 1
   ....:     return n_matches == 6
   ....: 

In [31]: match(phrase2)
Out[31]: True

In [32]: match(phrase3)
Out[32]: False

In [33]: match(phrase1)
Out[33]: False

答案 1 :(得分:0)

我认为你的代码是正确的,但问题是有N! (N!= N *(N-1)*(N-2)* .. * 2 * 1)N个元素的排列。

在你的情况下,你正在排列37个元素:

37!=13763753091226345046315979581580902400000000 

所以你的代码需要很长时间才能找到有用的答案。

更好的方法是尝试通过跟踪每种类型的可用字母的数量来构建有效的短语。

我们的想法是构建一个递归函数,尝试生成所有k-words短语,并给出每种字母类型的可用数量:

1)依次遍历词典中的每个单词

2)如果你没有足够的字母来制作这个单词,那么跳到下一个单词然后再回到步骤1

3)如果你有足够的字母,请制作一个包含剩余字母的新集合。

4)如果k = 1,那么你已到达递归的底部并可以打印结果

5)否则你可以递归调用函数从剩余字母的集合中创建一个k-1单词短语。

相关问题