使用Python在文件中查找具有特定字符串的行
我试图用python打印文本文件中的类别和页数 这是我到目前为止写的代码:使用Python在文件中查找具有特定字符串的行,python,Python,我试图用python打印文本文件中的类别和页数 这是我到目前为止写的代码: search = input("Which book are you looking for: ") file = open("books.txt","r") line_num = 0 reading = file.readlines() # for line in file: # if search in file: # NOT SURE HOW TO WRITE TO GET THE LINE NUMBER
search = input("Which book are you looking for: ")
file = open("books.txt","r")
line_num = 0
reading = file.readlines()
# for line in file:
# if search in file:
# NOT SURE HOW TO WRITE TO GET THE LINE NUMBER OF WHAT THE USER IS LOOKING FOR
book_category = line_num + 1
book_pages = line_num + 2
print(reading[book_category] , " " , reading[book_pages])
file.close()
这是文件(books.txt)
试试这个:
with open('books.txt') as fin :
lines = fin.readlines()
line_num = -1
for k,line in enumerate(lines) :
if line.find( search ) != -1 :
line_num = k
上面的代码将搜索书名中的用户输入,例如,如果用户输入“Gob”,则以下所有书籍都将匹配:“Goblin”、“Richard Gobbler的生活”等
如果需要精确匹配,请使用:
if line.lower().strip() == search.lower().strip() :
试试这个:
with open('books.txt') as fin :
lines = fin.readlines()
line_num = -1
for k,line in enumerate(lines) :
if line.find( search ) != -1 :
line_num = k
上面的代码将搜索书名中的用户输入,例如,如果用户输入“Gob”,则以下所有书籍都将匹配:“Goblin”、“Richard Gobbler的生活”等
如果需要精确匹配,请使用:
if line.lower().strip() == search.lower().strip() :
解决这个问题的一种方法是将字符串/书本分成两部分,即目标之前和之后的内容。然后将目标前面的所有内容按新行分割,并计算有多少行
def line_no(inp, target):
inp = inp.split(target)
#inp[0] = everything before your target
line_no = len(inp[0].split('\n')) #split everything before your target by line and get a count
#-1 for zero index
return line_no
statement = '''Hello
World
I
Am
A
Statement'''
line_no(statement, 'Am')
解决这个问题的一种方法是将字符串/书本分成两部分,即目标之前和之后的内容。然后将目标前面的所有内容按新行分割,并计算有多少行
def line_no(inp, target):
inp = inp.split(target)
#inp[0] = everything before your target
line_no = len(inp[0].split('\n')) #split everything before your target by line and get a count
#-1 for zero index
return line_no
statement = '''Hello
World
I
Am
A
Statement'''
line_no(statement, 'Am')