Я застрял в том, как искать название книги в текстовом файле, потому что между названиями есть пробелы.

Это текстовый файл, который я пытаюсь найти:

#Listing showing sample book details 
#AUTHOR, TITLE, FORMAT, PUBLISHER, COST?, STOCK, GENRE
P.G. Wodehouse, Right Ho Jeeves, hb, Penguin, 10.99, 5, fiction
A. Pais, Subtle is the Lord, pb, OUP, 12.99, 2, biography
A. Calaprice, The Quotable Einstein, pb, PUP, 7.99, 6, science
M. Faraday, The Chemical History of a Candle, pb, Cherokee, 5.99, 1, science
C. Smith, Energy and Empire, hb, CUP, 60, 1, science
J. Herschel, Popular Lectures, hb, CUP, 25, 1, science
C.S. Lewis, The Screwtape Letters, pb, Fount, 6.99, 16, religion
J.R.R. Tolkein, The Hobbit, pb, Harper Collins, 7.99, 12, fiction
C.S. Lewis, The Four Loves, pb, Fount, 6.99, 7, religion
E. Heisenberg, Inner Exile, hb, Birkhauser, 24.95, 1, biography
G.G. Stokes, Natural Theology, hb, Black, 30, 1, religion

Мой код:

desc = input('Enter the title of the book you would like to search for: ')
for bookrecord in book_list:
    if desc in bookrecord:
        print('Book found')        
    else:
        print('Book not found')
        break

Кто-нибудь знает, как это сделать?

-2
JJBANG458 5 Дек 2020 в 17:47

4 ответа

Лучший ответ

Ну вот:

def writeData(data):
    
    with open('file.txt', 'a') as w:
        w.write(data)

def searchData(title):
    data = ''
    title_list = []
    with open('file.txt') as r:
        data = r.read()
    
    title_list = data.split(', ')[1::6]
    print(title_list)
    
    stock = data.split(', ')[5::6]

    print(stock)
    
    if title in title_list:
        print('Book Found')

    else:
        print('Book Not Found')


writeData('P.G. Wodehouse, Right Ho Jeeves, hb, Penguin, 10.99, 5, fiction')
writeData('A. Pais, Subtle is the Lord, pb, OUP, 12.99, 2, biography')

searchData('Right Ho Jeeves')
-2
JacksonPro 5 Дек 2020 в 15:56

Вы можете использовать функцию разделения, чтобы удалить пробелы:

handle = open("book list.txt")#Open a file handle of the given file
            
for lines in handle:#A variable 'lines' that will iterate through all the variables in the file
    words = lines.split(,)#splits the file text into separate words and removes extra spaces.(the comma tells it to split where there are commas)
        
desc = input('Enter the title of the book you would like to search for: ')
        
for bookrecord in words:
    if desc in bookrecord:
        print('Book found')
else:
    print('Book not found')
         break

Исправьте отступ в коде перед его запуском, иначе он выдаст ошибку.

-1
Arya Man 5 Дек 2020 в 15:20

Если ваш файл - csv, то:

import pandas as pd

inp = input("Enter the books name: ")

bk = pd.read_csv('book_list.csv')#enter your file name
for row in bk.iterrows():
    if inp in row:
        print("Book found")
    else:
        print("Book not found")

Примечание: это будет работать, только если ваш файл - csv.

-1
Arya Man 5 Дек 2020 в 15:25

Вы можете прочитать свой файл в списке python , чтобы каждый раз, когда вы хотите найти в файле одно название книги или автора, вам не приходилось перезагружать файл снова и снова.

with open("file", "r") as file:
    data = file.readlines()

Это делает ваш код быстрым, если файл большой! Теперь вы можете просто найти то, что хотите найти:

text_to_find = "C. Smith"

for idx, line in enumerate(data):
    if text_to_find in line:
        print(f"{text_to_find} FOUND AT {idx} LINE")

Обратите внимание на использование f-строки !

-1
Mr. Hobo 5 Дек 2020 в 16:10