简体   繁体   中英

How can I print specific parts of a text file in python?

I have a text file, for example a database of multiple names + associated phone numbers/ages:

Name - Bob

Surname - Jenkins

Age - 32


Name - Harry

Surname - Beach

Age - 26


Name - Ethan

Surname - Hall

Age - 40

I make an input in python called 'Search', then look for any matches in the text file. How can I make it print the information for that person. For example in the input I put "Harry", so it searches in the text file for any lines saying "Harry" and prints their Name, surname, and Age.

Here is a script that can convert your text into a dictionary. With this you can search through various parameter easily.

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 will look like

[{'Name': 'Bob', 'Surname': 'Jenkins', 'Age': '32'}, {'Name': 'Harry', 'Surname': 'Beach', 'Age': '26'}, {'Name': 'Ethan', 'Surname': 'Hall', 'Age': '4'}]

As a side note, I would strongly recommend to use some database like SQLite (SQL), TinyDB (NoSQL) or heck, just a plain JSON file, instead of a text file.

This should work:

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

Just change the lookup variable to the desired name and it should print the name, surname and age.

This works if the text file is exactly how it is in your question. The amount of spaces between name, surname and age need to be 1.

Search Code

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

Test Code

Use a mixture of lower and upper case name spelling to show search is case insensitive

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("")

File db.txt

Name - Bob
Surname - Jenkins
Age - 32

Name - Harry
Surname - Beach
Age - 26

Name - Ethan
Surname - Hall
Age - 40

Output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM