好吧,所以对于类,我们有这个问题,我们需要能够对输入的字,从一个给定的文本文件(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
每次我尝试运行它只是返回一个空列表的程序,尽管我知道有存在字谜。 关于什么是错的任何想法?
PS的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
问题是,你正在使用readline
功能。 从文档:
file.readline = readline(...)
readline([size]) -> next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
这里的关键信息是“保留换行符”。 这意味着,如果你有一个包含单词的列表中的文件,每行一个,每个字是要与终端换行返回。 所以,当你拨打:
next = file.readline()
你没有得到example
,你得到example\n
,所以这永远不会匹配您的输入字符串。
一个简单的解决方法是调用strip()
从文件读出的线路的方法:
next = file.readline().strip()
while next != "":
isit = is_anagram(string, next)
if isit is True:
anagrams.append(next)
next = file.readline().strip()
file.close()
但是,有几个问题与此代码。 首先,启动file
是一个变量可怕的名字,因为这会掩盖蟒蛇file
模块。
而不是重复调用readline()
你最好采取的事实,即一个开放的文件是其产生文件的行的迭代器的优势:
words = open('wordlist.txt')
for word in words:
word = word.strip()
isit = is_anagram(string, word)
if isit:
anagrams.append(word)
words.close()
还要注意在这里,因为is_anagram
返回真或假,你并不需要的结果比较True
或False
(例如, if isit is True
)。 你可以简单地使用它自己的返回值。
哎呀,不用于循环使用:
import collections
def find_anagrams(x):
anagrams = [''.join(sorted(list(i))) for i in x]
anagrams_counts = [item for item, count in collections.Counter(anagrams).items() if count > 1]
return [i for i in x if ''.join(sorted(list(i))) in anagrams_counts]