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”,因为有些行不匹配。
- 如果该行包含关键字=,则打印这些结果并忽略那些不匹配的结果。
- 如果没有其他匹配,则转向其他。
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()
这是包含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”,因为有些行不匹配。
- 如果该行包含关键字=,则打印这些结果并忽略那些不匹配的结果。
- 如果没有其他匹配,则转向其他。
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()