如何从文本文件中找到字谜

时间:2019-04-24 06:03:48

标签: python-3.x

给定文本文件中的所有字谜。我试过了,但是代码不起作用。根本没有输出。

 def anagrams( s1, s2 ):
    s1_list = list(s1.lower())
    s1_list.sort()
    s2_list = list(s2.lower())
    s2_list.sort()

    if s1.lower() == s2.lower():
        return(False)
    elif s1_list == s2_list:
        return(True)
    else:
        return(False) 
        def find_all_anagrams( string ):
            anagrams_list = []
            with open("English.txt", "r") as fileObject:
                for line in fileObject: 
                    word = line.strip()
            if anagrams(string, word):
                anagrams_list.append(word)
                return anagrams_list

输出应打印文本文件中的所有字谜

1 个答案:

答案 0 :(得分:0)

代码中的缩进全部弄乱了。我尝试如下进行更正。

def anagrams( s1, s2 ):
    #convert the strings to lower case and sort them
    s1 = sorted(s1.lower())
    s2 = sorted(s2.lower())
    #If the string match, they are anagrams else they are not
    return s1 == s2

def find_all_anagrams( string ):
    anagrams_list = []
    with open("english.txt", "r") as fileObject:
        #Match each word in file against the string, and if it an anagram
        #append it to anagram list
        for line in fileObject:
            word = line.strip()
            if anagrams(string, word):
                anagrams_list.append(word)
    return anagrams_list

print(find_all_anagrams('abcd'))

如果输入文件如下,字符串为abcd

abcd
bcda
aaaa
bbbb
abdc
xxxx
x
y
z
aaabcd

输出将为

['abcd', 'bcda', 'abdc']