Python If == true statement only working on last line of readline

前端 未结 1 1706
攒了一身酷
攒了一身酷 2021-01-25 18:26

My function only says that the last word in a file of words is an anagram (the first helper function). But every word in the file is an anagram of the word I tested and returns

相关标签:
1条回答
  • 2021-01-25 18:45

    This is expected, based on the method you use to read a line (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.

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

    Well, that's all you'd need to change to get it working. Additionally, I'd also recommend using the 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
    

    It's better to use a 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).


    Incorporating @Christian Dean's suggestion in this answer, you can simplify your anagram function as well - call sorted and return the result in a single line:

    def is_anagram(a, b):
        return sorted(a) == sorted(b)
    
    0 讨论(0)
提交回复
热议问题