You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python文件处理问题:按出版年份过滤时整数比较失效

Python书籍年份过滤功能整数比较失效问题

我的Python代码可正常读取项目中的books.txt文件,但按出版年份过滤书籍时,整数比较操作无法返回准确结果。其中选项4(年份区间过滤)可正常工作,但选项1、2、3要么返回无结果,要么数据错误。

功能代码

def filter_by_release_year(self):
    try:
        year = int(input("Enter release year: "))
        current_year = datetime.datetime.now().year
        if year > current_year:
            print("Invalid year. Please enter a valid release year.")
            return
        self.file.seek(0)
        books = self.file.readlines()
        filtered_books = []
        second_year = 0
        choiceTwo = "0"
        print("\nFilter Options:")
        print(f'1. Books published in "{year}"')
        print(f'2. Books published in "{year}" and AFTER')
        print(f'3. Books published in "{year}" and BEFORE')
        print(f'4. Books published between "{year}" and "second year"')
        choiceTwo = input("Enter your filter option(1-4): ")
        if choiceTwo == "4":
            second_year = int(input("Enter second release year: "))
            if second_year > current_year:
                print("Invalid second year. Please enter a valid release year.")
        if second_year < year:
            temp = year
            year = second_year
            second_year = temp

        for book in books:
            book_info = book.strip().split(",")
            print(book_info)
            book_year: int = int(book_info[2])
            if choiceTwo == "1" and book_year == year: # Option 1
                filtered_books.append(f"{book.strip()}")
            elif choiceTwo == "2" and year <= book_year:  # Option 2
                filtered_books.append(f"{book.strip()}")
            elif choiceTwo == "3 " and book_year <= year:  # Option 3
                filtered_books.append(f"{book.strip()}")
            elif choiceTwo == "4" and year <= book_year <= second_year: # Option 4
                filtered_books.append(f"{book.strip()}")

        if not filtered_books:
            print("No books found matching the filter criteria.")
        else:
            print("Filtered Books:")
            for index, book in enumerate(filtered_books, start=1):
                print(f"{index}. {book}")
    except ValueError:
        print("Invalid input. Please enter a valid year.")
    except Exception as e:
        print(f"Error: Unable to filter books by release year - {e}")

选项1运行输出

Filter Options:
1. Filter by Book Title
2. Filter by Author
3. Filter by Release Year
4. Filter by Number of Pages
5. Sort Books
Enter your filter option: 3
Enter release year: 2000

Filter Options:
1. Books published in "2000"
2. Books published in "2000" and AFTER
3. Books published in "2000" and BEFORE
4. Books published between "2000" and "second year"
Enter your filter option(1-4): 1
No books found matching the filter criteria.

选项4运行输出(正常工作)

Filter Options:
1. Filter by Book Title
2. Filter by Author
3. Filter by Release Year
4. Filter by Number of Pages
5. Sort Books
Enter your filter option: 3
Enter release year: 2005

Filter Options:
1. Books published in "2005"
2. Books published in "2005" and AFTER
3. Books published in "2005" and BEFORE
4. Books published between "2005" and "second year"
Enter your filter option(1-4): 4
Enter second release year: 2010

Filtered Books:
1. Harry Potter ve Melez Prens,J.K. Rowling,2005,607
2. Harry Potter ve Ölüm Yadigarları,J.K. Rowling,2007,784
3. Kayıp Sembol,Dan Brown,2009,504
4. Zahir,Paulo Coelho,2005,208
5. A Thousand Splendid Suns,Khaled Hosseini,2007,368

调试代码及输出

调试代码片段

for book in books:
    book_info = book.strip().split(",")
    print(book_info)
    book_year: int = int(book_info[2])
    if book_year == year:
        print("equal\n")
    if book_year >= year:
        print("equal or bigger\n")
    if book_year <= year:
        print("equal or smaller\n")
    if choiceTwo == "1":
        print("1 is chosed")
    if choiceTwo == "2":
        print("2 is chosed")
    if choiceTwo == "3":
        print("3 is chosed")

调试输出

Filter Options:
1. Books published in "2000"
2. Books published in "2000" and AFTER
3. Books published in "2000" and BEFORE
4. Books published between "2000" and "second year"
Enter your filter option(1-4): 1
['Harry Potter ve Azkaban Tutsağı', 'J.K. Rowling', '1999', '435']
equal or bigger

1 is chosed
['Harry Potter ve Ateş Kadehi', 'J.K. Rowling', '2000', '766']
equal or bigger

1 is chosed
['Harry Potter ve Zümrüdüanka Yoldaşlığı', 'J.K. Rowling', '2003', '1107']
equal or bigger

1 is chosed

问题分析

从调试结果和代码可定位两个核心问题:

  1. 年份交换逻辑错误:if second_year < year:的判断未限定在选项4分支中。选择选项1、2、3时,second_year初始值为0,会触发交换逻辑,把用户输入的年份(如2000)和0交换,导致后续所有比较基于year=0执行——这是选项1找不到2000年书籍的根本原因。
  2. 选项3判断条件多空格:代码中choiceTwo == "3 "(引号内多一个空格),导致选择选项3时永远无法匹配该分支。

解决方案

1. 修正年份交换逻辑

将年份交换代码移至选项4分支内部,仅当用户选择区间过滤时才处理年份顺序:

if choiceTwo == "4":
    second_year = int(input("Enter second release year: "))
    if second_year > current_year:
        print("Invalid second year. Please enter a valid release year.")
    # 仅在选项4时交换年份顺序
    if second_year < year:
        temp = year
        year = second_year
        second_year = temp

2. 修正选项3判断条件

去掉"3 "中的空格,改为"3":

elif choiceTwo == "3" and book_year <= year:  # Option 3
    filtered_books.append(f"{book.strip()}")

修正后的完整函数

def filter_by_release_year(self):
    try:
        year = int(input("Enter release year: "))
        current_year = datetime.datetime.now().year
        if year > current_year:
            print("Invalid year. Please enter a valid release year.")
            return
        self.file.seek(0)
        books = self.file.readlines()
        filtered_books = []
        second_year = 0
        choiceTwo = "0"
        print("\nFilter Options:")
        print(f'1. Books published in "{year}"')
        print(f'2. Books published in "{year}" and AFTER')
        print(f'3. Books published in "{year}" and BEFORE')
        print(f'4. Books published between "{year}" and "second year"')
        choiceTwo = input("Enter your filter option(1-4): ")
        if choiceTwo == "4":
            second_year = int(input("Enter second release year: "))
            if second_year > current_year:
                print("Invalid second year. Please enter a valid release year.")
            # 仅在选项4时处理年份顺序
            if second_year < year:
                temp = year
                year = second_year
                second_year = temp

        for book in books:
            book_info = book.strip().split(",")
            book_year: int = int(book_info[2])
            if choiceTwo == "1" and book_year == year: # Option 1
                filtered_books.append(f"{book.strip()}")
            elif choiceTwo == "2" and year <= book_year:  # Option 2
                filtered_books.append(f"{book.strip()}")
            elif choiceTwo == "3" and book_year <= year:  # Option 3
                filtered_books.append(f"{book.strip()}")
            elif choiceTwo == "4" and year <= book_year <= second_year: # Option 4
                filtered_books.append(f"{book.strip()}")

        if not filtered_books:
            print("No books found matching the filter criteria.")
        else:
            print("Filtered Books:")
            for index, book in enumerate(filtered_books, start=1):
                print(f"{index}. {book}")
    except ValueError:
        print("Invalid input. Please enter a valid year.")
    except Exception as e:
        print(f"Error: Unable to filter books by release year - {e}")

内容的提问来源于stack exchange,提问作者Talha Burak Aydın

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:55:58