如何在文本文件中找到最长的单词?

Mal*_*l C 0 python python-3.x python-3.3

我创建了一个函数来查找文本文件中最长的单词,并在文本文件中找到可以由9个字母组成的最长单词.我是python的新手,我正在创建一个类似于倒计时的游戏.

我创建了一个函数来查找文本文件中最长的单词.我现在想要的是创建python代码以找到可以由9个字母组成的最长单词.

每个字母只能使用一次.因此,从'qugteroda',我应该得到rag outou,愤怒,out out,out read,outout,readout.我正在使用python 3.3

我的代码看起来像这样:

def Words():
    qfile=open('dict.txt','r')
    long=''
    for line in qfile:
    if len(line)>len(long):
        long=line
    return long
Run Code Online (Sandbox Code Playgroud)

Jos*_*ton 5

因此,您希望从字典中存在的一组字母中找到排序最长的组合.

为此,您将使用长度等于字符串长度的itertools.combinations().您将根据排序的字典检查所有这些组合,如果找不到匹配项,请减小组合长度.

您还希望将整个字典加载到一个集合中以减少搜索时间.我已将这组单词加载到字典中,其中键是排序字符串,值是具有相同排序表示的单词列表.

像这样的东西:

import itertools
from collections import defaultdict

words = defaultdict(list)
with open('/usr/share/dict/words') as qfile:
    for word in qfile:
        word = word.rstrip('\n').lower()
        words[''.join(sorted(word))].append(word)

def longest_anagram(term, words):
    search_length = len(term)
    term = sorted(term) # combinations maintains sort order
    while search_length > 0:
        for combo in itertools.combinations(term, search_length):
            search = ''.join(combo) # sort above means we dont need it here
            if search in words:
                return words[search]
        search_length -= 1
    return None

found = longest_anagram('qugteroda', words)
for w in found:
    print(w)
Run Code Online (Sandbox Code Playgroud)

为了完整起见,我应该提到这种方法适用于18个字母或更少的搜索字符串.如果你需要从一串大于18的字母中找到最长的字谜,你最好不要翻转算法,这样你就可以按照长度将字典单词排序到一个列表中.然后,您将遍历所有单词并检查它们是否存在于输入搜索字符串中 - 就像@ abarnert的答案一样.