這是我當前的代碼:
search=input('Enter a book title')
def read_book():
booksdata=[]
f=open('books2.txt', 'r')
for record in f:
cleanrecord=record.strip()
books=cleanrecord.split(',')
booksdata.append(books)
f.close()
return booksdata
read_book()
它會打開一個文本檔案,其中存盤的資料如下:
1, The Hunger Games, Adventure, Suzanne Collins, 1/08/2006, coai
2, Harry Potter and the Order of the Phoenix, Fantasy, J.K Rowling, 25/09/2021, ajyp
我正在嘗試對其進行編程,因此如果用戶輸入“饑餓”,則將列印出包含饑餓的整個串列:
['1', ' The Hunger Games', ' Adventure', ' Suzanne Collins', ' 1/08/2006', ' coai']
uj5u.com熱心網友回復:
您需要檢查您的輸入是否在每一行中
search=input('Enter a book title')
def read_book():
booksdata=[]
f=open('books2.txt', 'r')
for record in f:
if search in record: # check
cleanrecord=record.strip()
books=cleanrecord.split(',')
booksdata.append(books)
f.close()
return booksdata
result = read_book()
print (result)
輸出:
[['1', ' The Hunger Games', ' Adventure', ' Suzanne Collins', ' 1/08/2006', ' coai']]
uj5u.com熱心網友回復:
for d in read_book():
if any(['hunger' in w.lower() for w in d]):
print(d)
該函式any()接受一個布林值串列作為引數,如果其中任何一個值為真,則回傳 True。我們提供給它的串列為 d 中的每個元素存盤字串 'hunger' 是否存在于該元素中(是該元素的子字串)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/373303.html
上一篇:永久添加GitLab個人訪問令牌
