Python If == true 语句仅适用于 readline 的最后一行

2023-12-03

我的函数仅表示单词文件中的最后一个单词是字谜(第一个辅助函数)。但文件中的每个单词都是我测试的单词的字谜词,并通过主函数之外的辅助函数独立返回 true。我不确定这是否与/n是字符串的一部分,然后它解释了这一点,但我尝试放入一个 if 语句,表示如果它在其中,则将其删除,但这也不起作用。我还做了测试以确保它贯穿了中的每个单词.txt文件,确实如此。

def is_anagram(string1, string2):
    """Returns True if the two strings are anagrams of eachother.

    str, str -> bool"""
    if sorted(string1)==sorted(string2):
        return True
    else:
        return False


def find_anagrams(word):
    final = []
    content = open("small_list.txt")
    content.close
    while True:
        line = content.readline()
        print(line)
        if is_anagram(word, line) == True:
            print("bruh")
            final.append(line)
        elif line == '':
             break
    return final

根据您用来读取行的方法,这是预期的(file.readline)。来自文档:

f.readline()从文件中读取一行;换行符 (\n) 留在字符串的末尾,并且仅在最后一个被省略 如果文件不以换行符结尾,则为文件的行。

Your line有一个尾随换行符,但是word当然不会。所以,最后,你需要改变的是:

line = content.readline().rstrip()

好吧,这就是您需要更改的全部内容让它发挥作用。此外,我还建议使用with...as上下文管理器来处理文件 I/O。这是很好的做法,你会为此感谢自己。

with open("small_list.txt") as f:
    for line in f:
        if is_anagram(word, line.rstrip()):
            ... # do something here

最好使用for循环来迭代文件的行(而不是while,更干净)。另外,不需要显式调用f.close()当您使用上下文管理器时(您当前没有这样做,您只是引用该方法而不实际调用它)。


合并@Christian Dean's建议在这个答案中,您也可以简化您的字谜函数 - 调用sorted and在一行中返回结果:

def is_anagram(a, b):
    return sorted(a) == sorted(b)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python If == true 语句仅适用于 readline 的最后一行 的相关文章

随机推荐