我想返回'listofwords.txt‘中的单词列表,这些单词是字符串'b’的字谜。
def find_anagrams(a,b): ##a is the listofwords.txt
f=open('listofwords.txt', 'r')
for line in f:
word=line.strip()
wordsorted= ''.join(sorted(line))
for word in f:
if wordsorted == ''.join(sorted(word)):
print word为什么它只是给我在名单中的第一个单词的字谜?
此外,如果没有找到字谜,我如何返回消息?
发布于 2015-03-08 22:15:08
第二个for是不正确的。你正在比较单词排序和‘.’.join(排序(Word)),这是相同的事情。这应该更好地发挥作用:
def find_anagrams(a, b):
f = open(a, 'r')
for line in f:
word = line.strip()
wordsorted = ''.join(sorted(word))
if wordsorted == ''.join(sorted(b)):
print word现在,确保关闭文件(或者更好地使用with语句)。
编辑:关于返回消息的,最好的方法实际上是返回找到的字谜列表。然后,您将决定如何处理这些单词(要么打印它们,要么在列表为空时打印消息,或者任何您想要的内容)。所以可能就像
def find_anagrams(a, b):
anagrams = []
with open(a, 'r') as infile:
for line in f:
word = line.strip()
wordsorted = ''.join(sorted(word))
if wordsorted == ''.join(sorted(b)):
anagrams.append(word)
return anagrams然后你就可以把它当作
anagrams = find_anagrams('words.txt', 'axolotl')
if len(anagrams) > 0:
for anagram in anagrams:
print anagram
else:
print "no anagrams found"发布于 2015-03-08 22:17:04
您正在内部循环中重用文件迭代器f。一旦内部循环完成,f就会耗尽,您将立即退出外部循环,因此实际上无法通过第一行。
如果您希望在文件中的所有行上有两个独立的循环,一个解决方案(我相信这个问题可以更有效地解决)是首先将这些行读入列表中,然后迭代列表:
with open('listofwords.txt') as f: # note: 'r' is the default mode
lines = f.readlines() # also: using `with` is good practice
for line in lines:
word = line.strip()
wordsorted = ''.join(sorted(line))
for word in lines:
if word == ''.join(sorted(word)):
print word编辑:我的代码解决不了你说的问题(我首先误解了它,请参阅马提斯对正确代码的回答),但我的答案仍然解释了为什么你只能得到文件中第一个单词的字谜。
https://stackoverflow.com/questions/28931992
复制相似问题