【发布时间】:2012-10-19 09:08:40
【问题描述】:
我的问题是是否有可能改进此代码,以便我的 定义的单词列表可以更快地搜索整个 word_list.txt 文件。有人告诉我,有一种方法可以通过将文件放入适当的数据结构中对所有 14 个单词进行一次迭代来完成此操作。
word_list = ['serve','rival','lovely','caveat','devote',\
'irving','livery','selves','latvian','saviour',\
'observe','octavian','dovetail','Levantine']
def sorted_word(word):
"""This return the sorted word"""
list_chars = list(word)
list_chars.sort()
word_sort = ''.join(list_chars)
return word_sort
print("Please wait for a few moment...")
print()
#Create a empty dictionary to store our word and the anagrams
dictionary = {}
for words in word_list:
value = [] #Create an empty list for values for the key
individual_word_string = words.lower()
for word in open ('word_list.txt'):
word1 = word.strip().lower() #Use for comparing
#When sorted words are the same, update the dictionary
if sorted_word(individual_word_string) == sorted_word(word1):
if word1[0] == 'v':
value.append(word.strip()) #Print original word in word_list
tempDict = {individual_word_string:value}
dictionary.update(tempDict)
#Print dictionary
for key,value in dictionary.items():
print("{:<10} = {:<}".format(key,value))
由于新用户限制,我无法发布我的结果图片。顺便说一句,结果应该为每个单词打印出以 v 开头的字谜。很高兴为改进此代码提供任何帮助。
【问题讨论】:
-
您可以简单地将单词排序为
word = ''.join(sorted(word))而不是函数 -
您可能希望从交换两个循环开始——外部循环遍历文件中的单词,内部循环将其与单词列表进行比较。
-
我认为这也更有意义。谢谢
-
不要使用那些反斜杠来继续一行。 Python 会自动延续
()、[]和{}之间的行。一般来说,永远不要使用反斜杠继续。如果您必须继续一行,请在其周围添加括号。
标签: python python-3.x