假設特定領域我有一個名爲abc.txt
文件,其中包含了以下數據。我是一個新手。所以,請大家幫忙搜索文本文件
Nathan Johnson 23 M
Mary Kom 28 F
John Keyman 32 M
Edward Stella 35 M
做fname
,lname
,age
,gender
與他們相關的指標?因爲我的要求是,如果用戶選擇通過名字搜索條件,應該在第一名稱列只搜索或選擇查詢條件如性別,它應該在性別搜索和顯示整個記錄。我該怎麼做呢?
#!usr/bin/python
import sys
class Person:
def __init__(self, firstname=None, lastname=None, age=None, gender=None):
self.fname = firstname
self.lname = lastname
self.age = age
self.gender = gender
def display(self):
found = False
n1 = raw_input("Enter for Search Criteria\n1.FirstName == 2.LastName == 3.Age == 4.Gender : ")
print "Not a valid input"
if n1.isdigit():
n = int(n1)
else:
print "Enter Integer only"
if n == 0 or n>4:
print "Enter valid search "
if n == 1:
StringSearch = raw_input("Enter FirstName :")
for records in list_of_records:
if StringSearch in records.fname:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
if n == 2:
StringSearch = raw_input("Enter LastName :")
for records in list_of_records:
if StringSearch in records.lname:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
if n == 3:
StringSearch = raw_input("Enter Age :")
for records in list_of_records:
if StringSearch in records.age:
if not found:
print "No matched record"
if n == 4:
StringSearch = raw_input("Enter Gender(M/F) :")
for records in list_of_records:
if StringSearch in records.gender:
found = True
print records.fname, records.lname, records.age, records.gender
if not found:
print "No matched record"
f= open("abc","r")
list_of_records = [Person(*line.split()) for line in f]
#for record in list_of_records:
for per in list_of_records:
per.display()