[英]How can I print specific parts of a text file in python?
我有一個文本文件,例如一個包含多個姓名 + 相關電話號碼/年齡的數據庫:
姓名 - 鮑勃
姓氏 - 詹金斯
年齡 - 32
姓名 - 哈利
姓氏 - 海灘
年齡 - 26
姓名 - 伊森
姓氏 - 霍爾
年齡 - 40
我在 python 中輸入一個名為“搜索”的輸入,然后在文本文件中查找任何匹配項。 我怎樣才能讓它打印那個人的信息。 例如,在輸入中我輸入了“Harry”,因此它在文本文件中搜索任何說“Harry”的行並打印他們的姓名、姓氏和年齡。
這是一個可以將您的文本轉換為字典的腳本。 有了這個,您可以輕松搜索各種參數。
with open('db.txt') as f:
file = f.readlines()
db = []
for i in range(0, len(file), 4):
d = {}
d[file[i].split(" - ")[0]]=file[i].split(" - ")[1][:-1]
d[file[i+1].split(" - ")[0]]=file[i+1].split(" - ")[1][:-1]
d[file[i+2].split(" - ")[0]]=file[i+2].split(" - ")[1][:-1]
db.append(d)
print(db)
db
看起來像
[{'Name': 'Bob', 'Surname': 'Jenkins', 'Age': '32'}, {'Name': 'Harry', 'Surname': 'Beach', 'Age': '26'}, {'Name': 'Ethan', 'Surname': 'Hall', 'Age': '4'}]
作為旁注,我強烈建議使用一些數據庫,如 SQLite (SQL)、 TinyDB (NoSQL) 或 heck,只是一個普通的 JSON 文件,而不是文本文件。
這應該有效:
lookup = 'Bob'
a=[]
b=[]
myFile=open('myFile.txt', 'r')
num_lines = sum(1 for line in open('myfile.txt'))
lines = myFile.read().splitlines()
for i in range(num_lines):
if lookup in lines[i] and "Name" in lines[i]:
a.append(lookup)
b.append(i)
for i in range (len(a)):
print("Name: "+a[0])
print(lines[b[0]+2])
print(lines[b[0]+4])
只需將查找變量更改為所需的名稱,它就會打印姓名、姓氏和年齡。
如果文本文件與您的問題完全相同,則此方法有效。 姓名、姓氏和年齡之間的空格數需要為 1。
搜索代碼
import re
def lookup(filename, findname):
" Looks up findname in text file "
with open(filename, 'r') as f:
for line in f:
# match line of the form: Name - {findname}
# make case insensitive by making first letter lowercase, other letters lower case
if re.match(f'^Name - {findname.title()}', line):
name = line.rstrip().split()[-1] # Get name line
surname = next(f).rstrip().split()[-1] # next line is surname
age = next(f).rstrip().split()[-1] # next line is age
return name, surname, age # result
break
else:
return None # Not found in text file
測試代碼
混合使用大小寫名稱拼寫來顯示搜索不區分大小寫
for search_name in ['Bob', 'bob', 'mary', 'harry']:
found = lookup('db.txt', search_name)
print(f"Search Result for {search_name}")
if found:
name, surname, age = found
print(f"Name: {name} {surname}\nAge {age}")
else:
print(f"{search_name} not found")
print("")
文件 db.txt
Name - Bob
Surname - Jenkins
Age - 32
Name - Harry
Surname - Beach
Age - 26
Name - Ethan
Surname - Hall
Age - 40
輸出
Search Result for Bob
Name: Bob Jenkins
Age 32
Search Result for bob
Name: Bob Jenkins
Age 32
Search Result for mary
mary not found
Search Result for harry
Name: Harry Beach
Age 26
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.