Python If == true语句仅在readline的最后一行有效 [英] Python If == true statement only working on last line of readline
问题描述
我的函数只说单词文件中的最后一个单词是一个字谜(第一个辅助函数).但是文件中的每个单词都是我测试过的单词的一个字谜,通过主函数之外的helper函数独立返回true.我不确定它是否与/n
是字符串的一部分有关,然后才考虑了这一点,但是我尝试放入一个if语句,说要删除它是否在字符串中那里,那也不起作用.我还进行了测试,以确保它遍历 .txt
文件中的每个单词,并且确实如此.
def is_anagram(string1,string2):如果两个字符串彼此相同,则"返回True.str,str->布尔"如果sorted(string1)== sorted(string2):返回True别的:返回Falsedef find_anagrams(word):最终= []内容=打开("small_list.txt")content.close而True:行= content.readline()打印(行)如果is_anagram(word,line)== True:打印("bruh")final.append(行)省略号行=='':休息返回最终
根据您用于读取行的方法( file.readline
),这是预期的.从文档:
f.readline()
从文件中读取一行;换行符(\ n
)留在字符串的末尾,仅在末尾省略如果文件未以换行符结尾,则为该行.
您的 line
带有尾随换行符,但是 word
当然没有.因此,最后,您需要更改的只是:
line = content.readline().rstrip()
好吧,这就是您要做的所有更改,以使其正常工作.另外,我还建议使用 with ... as
上下文管理器来处理文件I/O.这是一个好习惯,您会为此感到感谢的.
,其中open("small_list.txt")为f:对于f中的行:如果is_anagram(word,line.rstrip()):...#在这里做点事
最好使用 for
循环遍历文件的行(而不是 while
,这更干净).此外,在使用上下文管理器时,也无需显式调用 f.close()
(您当前未在执行此操作,仅引用该方法而未实际调用它).>
并入@Christian Dean的
This is expected, based on the method you use to read a line ( Your Well, that's all you'd need to change to get it working. Additionally, I'd also recommend using the It's better to use a Incorporating @Christian Dean's suggestion in this answer, you can simplify your anagram function as well - call
这篇关于Python If == true语句仅在readline的最后一行有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!file.readline
). From the 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
has a trailing newline, but word
certainly does not. So, in the end, all you'd need to change is:line = content.readline().rstrip()
with...as
context manager to handle file I/O. It's good practice, and you'll thank yourself for it.with open("small_list.txt") as f:
for line in f:
if is_anagram(word, line.rstrip()):
... # do something here
for
loop to iterate over the lines of a file (rather than a while
, it's cleaner). Also, there's no need to explicitly call f.close()
when you use a context manager (you're not currently doing it, you're only referencing the method without actually calling it).
sorted
and return the result in a single line:def is_anagram(a, b):
return sorted(a) == sorted(b)