gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:04:50 25 4
gpt4 key购买 nike

我的函数仅表示单词文件中的最后一个单词是字谜(第一个辅助函数)。但文件中的每个单词都是我测试的单词的字谜词,并通过主函数之外的辅助函数独立返回 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),这是预期的。来自 documentation :

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.

您的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 suggestion在此答案中,您还可以简化您的字谜函数 - 调用 sorted 在一行中返回结果:

def is_anagram(a, b):
return sorted(a) == sorted(b)

关于Python If == true 语句仅适用于 readline 的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49185754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com