簡體   English   中英

CSV 如果/否則無法正常工作 Python

[英]CSV Search | If / Else not working properly Python

這是包含 id、姓名、作者、主題和發布日期的 csv 文件示例內容。

2105001,Engineering Mechanics,Bela Imre Sandor,Engineering Mechanics,1983
2105002,Statics and Mechanics of Materials (2nd Edition),"William F. Riley, Leroy D. Sturges, Don H. Morris",Engineering Mechanics,2001
2105003,A Concise Introduction to Mechanics of Rigid Bodies,Loulin Huang,Engineering Mechanics,2011
2105004,Dynamics of Particles and Rigid Bodies,Mohammed F. Daqaq,Engineering Mechanics,2018
2105005,Engineering Sciences,Marcialito Modina Valenzona,Science,2002

這是代碼。 問題是即使有匹配的結果,代碼也會不斷轉向“else”,因為某些行不匹配。

  1. 就像如果該行包含關鍵字 = 打印那些結果並忽略那些不匹配的結果。
  2. 如果沒有其他匹配,則轉向其他。
def linear_search_name():
  bookname=input("Enter Title of the Book: ")
  bookfile=csv.reader(open("books.csv", "r"))
  for row in bookfile:
    if bookname.casefold() in row[1].casefold():
     print("ID:", row[0],"\n", row[1],"\n",row[2],"\n",row[3],"\n",row[4],"\n")
    else:
      print("try again")
      linear_search_name()

菜鳥問題,但我希望有人可以提供幫助。 非常感謝!!

代碼片段應該適合您:

import csv
def linear_search_name():
    bookname=input("Enter Title of the Book: ")
    bookfile=csv.reader(open("copilot-test/stack3.csv", "r"))
    match_flag = False
    for row in bookfile:
        if bookname.casefold() in row[1].casefold():
            print("ID:", row[0],"\n", row[1],"\n",row[2],"\n",row[3],"\n",row[4],"\n")
            match_flag = True
    else:
        if not match_flag:
            print("try again")
            linear_search_name()
    
linear_search_name()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM