[英]How to print strings from a text file,separated by new line in Python
I'm new in Python and i'm challenging myself by making an online library management with prompt for the 1st phase.I'm stacked in search function.I have found how to print a user's input,but i can't find how to print and the following data.I want to search a book by name.If book's name is in the text,i want to print the details of the book,like author,isbn etc.我是 Python 新手,我正在挑战自己,通过在线图书馆管理进行第一阶段的提示。我在搜索功能中堆积如山。我找到了如何打印用户输入的方法,但我找不到方法打印和以下数据。我想按名称搜索一本书。如果书名在文本中,我想打印这本书的详细信息,如作者、isbn 等。
Here is the following code i have made:这是我制作的以下代码:
def search():
search_book = input('Search a book: ')
with open('library.txt', mode='r', encoding='utf-8') as f:
index = 0
for line in f:
index += 1
if search_book in line:
print(f'{search_book} is in line {index}')
for details in range(index,index+5):
print(line[details])
And this is the text file's data:这是文本文件的数据:
FIRST
ME
9781234
2000
Science
SECOND
YOU
9791234
1980
Literature
It is separated by new line.As example a user input the name FIRST and the result will be:它由新行分隔。例如,用户输入名称 FIRST,结果将是:
FIRST
ME
9781234
2000
Science
There are two file options we can consider,我们可以考虑两个文件选项,
# ---------test.csv -------------
# BookName, ItemCode, Price
# Book1, 00012, 14.55
# Book2, 00232, 55.12
# -----End Csv-------------------
import csv
def read_csv(filename:str):
file_contents = None
# reading csv file
with open(filename, 'r') as csvfile:
file_contents = csv.reader(csvfile)
return file_contents
def search(file_contents, book_name:str):
if not file_contents:
return None
for line in file_contents:
if book_name in line:
return line
if __name__ == '__main__':
file_contents = read_csv('test.csv')
line = search(file_contents, 'ME')
print(line if line else 'No Hit Found')
import json
def read_json(filename:str) -> dict:
with open(filename) as json_file:
all_books = json.load(json_file)
return all_books
def search(all_books:dict, book_name:str):
for book_id, book_details in all_books.items():
if book_details['Name'] == book_name:
return book_details
return None
if __name__ == '__main__':
all_books = read_json('books.json')
book = search(all_books, 'YOU')
print(book if book else 'Not hit found')
If your file contents can't change, then I will go with @tripleee suggestion above.如果您的文件内容无法更改,那么我将采用上面的@tripleee 建议。 Good luck.
祝你好运。
You are reading a line at a time, and looping over the first line's contents.您一次阅读一行,并循环阅读第一行的内容。 At this point in the program, there are not yet any additional lines.
此时在程序中,还没有任何额外的行。 But a fix is relatively easy:
但是修复相对容易:
def search():
search_book = input('Search a book: ')
with open('library.txt', mode='r', encoding='utf-8') as f:
index = 0
print_this_many = 0
for line in f:
index += 1
if search_book in line:
print(f'{search_book} is in line {index}')
print_this_many = 5
if print_this_many:
print(line, end='')
print_this_many -= 1
We don't have the next lines in memory yet, but we can remember how many of them to print as we go ahead and read more of them.我们的内存中还没有下一行,但是我们可以记住要打印多少行并继续阅读更多的行。 The
print_this_many
variable is used for this: When we see the title we want, we set it to 5 (to specify that this and the next four lines should be printed). print_this_many
变量用于此:当我们看到我们想要的标题时,我们将其设置为 5(指定应打印此行和接下来的四行)。 Now, each time we read a new line, we check if this variable is positive;现在,每次我们读到一个新行时,我们检查这个变量是否为正; if it is, we print the line and decrement the variable.
如果是,我们打印该行并递减变量。 When it reaches zero, we will no longer print the following lines.
当它达到零时,我们将不再打印以下行。 This allows us to "remember" across iterations of the
for
loop which reads each new line whether we are in the middle of printing something.这允许我们在
for
循环的迭代中“记住”每个新行是否我们正在打印某些内容。
A much better solution is to read the database into memory once, and organize the lines into a dictionary, for example.例如,更好的解决方案是将数据库读入内存一次,然后将行组织成字典。
def read_lib(filename):
library = dict()
with open(filename) as lib:
title = None
info = []
for line in lib:
line = line.rstrip('\n')
if title is None:
title = line
elif line == '':
if title and info:
library[title] = info
title = None
else:
info.append(line)
def search(title, library):
if title in library:
return library[title]
else:
return None
def main():
my_library = read_lib('library.txt')
while True:
sought = input('Search a book: ')
found = search(sought, my_library)
if found:
print('\n'.join(found))
else:
print('Sorry, no such title in library')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.