Optimization 如何在字符串中查找非连续字符?
我有一个字典文本,我正试图在这个字典文本中找到包含指定字符的最长单词。字母将由用户输入。例如,如果用户输入红色,程序将必须找到包含r、e和d的最长单词。我能够找到包含r、e或d的单词。 如何缩小前提,以便存储的单词包含用户输入的所有字母,而不管其输入顺序如何?您可以尝试以下方法:Optimization 如何在字符串中查找非连续字符?,optimization,Optimization,我有一个字典文本,我正试图在这个字典文本中找到包含指定字符的最长单词。字母将由用户输入。例如,如果用户输入红色,程序将必须找到包含r、e和d的最长单词。我能够找到包含r、e或d的单词。 如何缩小前提,以便存储的单词包含用户输入的所有字母,而不管其输入顺序如何?您可以尝试以下方法: letter = input("Please enter the letters to include: ") data_file = open("dictionary.txt").read().splitlines
letter = input("Please enter the letters to include: ")
data_file = open("dictionary.txt").read().splitlines()
words = [i for i in data_file if all(b in i for b in letter)]
print(max(words, key = len))
该算法循环遍历单词列表,并创建一个新列表,其中包含用户输入的每个字母的所有单词。然后,代码从过滤列表中查找最长的单词。您可以使用内置类型简化和加速您想要执行的操作,因为它们使得快速测试文件的每个单词中是否包含所有字母变得很简单。我还建议您使用语句自动确保文件已关闭
如果dictionary.txt文件的格式是每行一个单词,则可以加快速度。但是,由于您从未描述过它是什么,所以下面的内容并不假设并且应该适用于文件的每一行上是否有一行或多行
dict_filename = "dictionary.txt"
outp_filename = "find_right_words.txt"
# user's input
letters = input("Please enter the letters to include: ")
letters = set(letters) # convert string to set of characters
print("searching for letters: {}".format(', '.join(sorted(letters))))
# find all words in dictionary file that contain all the letters and store them in a file
with open(dict_filename, "r") as data_file, \
open(outp_filename, "w") as find_right_words:
for line in data_file:
for word in line.split():
if letters.issubset(word): # all letters in word?
find_right_words.write(word+'\n')
print("file {!r} created".format(outp_filename))
但是,如果您只想查找包含所有字母的最长单词,那么实际上不需要创建find_right_words.txt文件,因为这可以在检查文件中的单词的同时确定
我的意思是:
# find longest word in dictionary file that contains all the letters
with open(dict_filename, "r") as data_file:
longest_word_len = 0
for line in data_file:
for word in line.split():
if(len(word) > longest_word_len # is word longer than longest word...
and letters.issubset(word)): # and all letters in it?
longest_word, longest_word_len = word, len(word)
print("longest word found: {!r}".format(longest_word))
请注意,如果有多个相同长度的单词包含所有字母,这将忽略除第一个以外的所有字母。dictionary.txt文件的内容格式是什么?数据文件中的for单词:是否每次读取文件一行,而不是按单词读取?这有关系吗?