【发布时间】:2015-05-06 06:47:39
【问题描述】:
好的,所以对于课堂我们有这个问题,我们需要能够输入一个单词,并且从给定的文本文件 (wordlist.txt) 中,将使用文件中找到的该单词的任何字谜来制作一个列表。
到目前为止,我的代码如下所示:
def find_anagrams1(string):
"""Takes a string and returns a list of anagrams for that string from the wordlist.txt file.
string -> list"""
anagrams = []
file = open("wordlist.txt")
next = file.readline()
while next != "":
isit = is_anagram(string, next)
if isit is True:
anagrams.append(next)
next = file.readline()
file.close()
return anagrams
每次我尝试运行程序时,它都会返回一个空列表,尽管我知道存在字谜。有什么想法吗?
附: is_anagram 函数如下所示:
def is_anagram(string1, string2):
"""Takes two strings and returns True if the strings are anagrams of each other.
list,list -> string"""
a = sorted(string1)
b = sorted(string2)
if a == b:
return True
else:
return False
我正在使用 Python 3.4
【问题讨论】:
-
我认为换行符可能会导致问题。您需要将其从行尾删除。
标签: python string file text anagram