def is_anagram(s1,s2):
L1 = list(s1)
L2 = list(s2)
return sorted(L1) == sorted(L2)
def read_words():
fin = open('words.txt')
for line in fin:
line = fin.readline()
word = line.strip()
for line1 in fin:
line1 = fin.readline()
word1 = line1.strip()
if is_anagram(word,word1):
print(word, word1)
read_words()
当我运行它时,它什么也没有显示(甚至没有错误)。我确信word.txt包含一些字谜。我不知道为什么这行不通。请有人帮忙。
words.txt看起来像这样:
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
aardvark
aardvarks
aardwolf
aardwolves
aas
aasvogel
aasvogels
aba
abaca
abacas
abaci
aback
abacus
abacuses
abaft
abaka
abakas
abalone
abalones
abamp
abampere
abamperes
abamps
abandon
abandoned
abandoning
abandonment
abandonments
abandons
abas
abase
abased
abasedly
abasement
abasements
abaser
abasers
abases
abash
abashed
abashes
abashing
abasing
abatable
abate
abated
abatement
abatements
abater
答案 0 :(得分:5)
fin
不是列表。每行只产生一次。您的两个循环不会独立地遍历它。
如果要多次迭代,请首先将这些行读入列表。一个列表可以重复多次。
def read_words():
with open('words.txt') as fin:
lines = [line.strip() for line in fin]
for line in lines:
for line1 in lines:
if line!=line1 and is_anagram(line, line1):
print(line,line1)
(这假定每个单词在文本文件中都位于单独的行上。)