巨蟒:在文本文件中搜索单词,其中单词之间包含空格



我一直纠结于如何在文本文件中搜索书名,因为书名之间有空格。

这是我试图搜索的文本文件:

#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

有人知道怎么做吗?

您可以使用split函数来删除空格:

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

在运行之前修复代码中的缩进,否则会出现错误。

如果您的文件是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 时,这才会起作用

您可以将文件读取到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-string的使用!

开始:

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')

最新更新