所有的排列都显示的不仅仅是英语

2024-09-28 22:04:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到一个简单的方法来解决一个anagram和显示这些anagram的英文单词在返回页。目前,这显示在解算器页面上的排列,有些工作,但我想显示那些只是实际的话

任何建议都非常感谢

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template('main.html')
    else:
        myLetters = request.form['letters']
        myLetters = ''.join(sorted(myLetters))
        myLetters = myLetters.strip()
        myWords = []
        myLetterList = list(myLetters)
        lettersLength = len(myLetterList)
        myWords = [''.join(result) for result in permutations(myLetters)]

        with open("/usr/share/dict/words") as defaultWords:
            for word in myWords:
                if word not in defaultWords:
                    myWords.remove(word)

        return render_template('solver.html', myLetters = myLetters, myWords = myWords)

Tags: ingetreturnifrequesthtmltemplateresult
2条回答

问题是:

if word not in defaultWords:

对文件使用in运算符会产生意外的结果

文件不支持__contains__,但它们的行为类似于行序列,因此if word in file只是在行上迭代,并产生意外的效果:

In [1]: f = open('/usr/share/dict/words')

In [2]: 'black\n' in f
Out[2]: True

In [3]: 'black\n' in f
Out[3]: False

In [4]: f.seek(0)

In [5]: 'black\n' in f
Out[5]: True

相反,在文件中创建一组所有单词(使用strip清除多余的空白):

with open('/usr/share/dict/words') as f:
    words = set(line.strip() for line in f)

并使用words进行查找


编辑:一旦设置好,您可能会尝试执行以下操作:

for word in myWords:
    if word not in words:
        myWords.remove(word)

但是在遍历列表的同时编辑它是一个badidea。相反,您可以在副本上迭代:

for word in list(myWords):
    if word not in words:
        myWords.remove(word)

瞧,它起作用了。但是,嘿,words现在是一个集合了,那么为什么还要麻烦循环呢?您可以使用^{}简单地说:

return words.intersection(myWords)

练习:如何避免将整个排列列表myWords同时保存在内存中

再次感谢@Kos。我的解决方式有点不同。虽然它不是超级漂亮,它的工作。在部署过程中,我不得不将/usr/share/dict/words更改为包中包含的文件,但除此之外,它还可以工作。如果您喜欢anagrams.mnickey.com或者这里的回购github.com/mnickey/anagrams,您可以在这里看到它的作用

""" This is setting up the control dictionary to read against """
from collections import defaultdict
words = defaultdict(list)
with open("dictionary") as f:
    for word in f:
        word=word.strip()
        words[''.join(sorted(word))].append(word)

@app.route('/', methods=['GET', 'POST'])
@app.route('/anagrams/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template('main.html')
    else:
        #this is the original set of letters that I want anagrams for
        myLetters = request.form['letters']
        # some cleanup on those letters
        myLetters = ''.join(sorted(myLetters))
        # then assign those letters to 'word'
        word = myLetters.strip().lower()

        """ This is where I need to check the letter sets against the control group """
        myWords =  words[''.join(sorted(word))]
        return render_template('solver.html', myLetters = myLetters, myWords = myWords)

相关问题 更多 >