简体   繁体   English

为什么这个python代码不打印字谜?

[英]why this python code doesn't print anagrams?

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()

When I run this it doesn't showup anything(not even a error).I am sure that words.txt include some anagrams.I can't figure out why this doesn't work.Please someone help. 当我运行它时,它什么也不会显示(甚至没有错误)。我确信word.txt包含一些字谜。我不知道为什么这不起作用,请有人帮忙。

words.txt looks like this: 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

fin isn't a list. fin不是一个清单。 It only yields each line once. 每行只产生一次。 Your two loops aren't going to iterate through it independently. 您的两个循环不会独立地遍历它。

If you want to iterate through it multiple times, read the lines into a list first. 如果要多次迭代,请先将这些行读入列表。 A list can be iterated multiple times. 一个列表可以重复多次。

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)

(This assumes that each word is on a separate line in your text file.) (这假定每个单词在文本文件中都位于单独的行上。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM