在文本文件中搜索特定字段

时间:2013-10-21 09:21:48

标签: python

假设我有一个名为abc.txt的文件,其中包含以下数据。我是新手。所以请帮忙

Nathan  Johnson 23 M
Mary    Kom     28 F
John    Keyman  32 M
Edward  Stella  35 M

fnamelnameagegender是否有与之关联的索引?因为我的要求是,如果用户通过名字选择搜索条件,它应仅搜索名字列或选择搜索条件作为性别,它应搜索性别并显示整个记录。我该怎么办?

#!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()

2 个答案:

答案 0 :(得分:1)

如果您想通过特定信息进行搜索,可以执行此类操作。因此,用户希望在firstname中搜索John。这就是你要做的事情:

#!usr/bin/python
import sys
class Records:
    def __init__(self, firstname, lastname, age, gender):
        self.fname = firstname
        self.lname = lastname
        self.age = age
        self.gender = gender

f= open("abc","r")
list_of_records = [Records(*line.split()) for line in f]
search_term = "John"
for record in list_of_records:
    if record.firstname == search_term:
        print "We found him!"
        print record.firstname, record.lastname, record.age, record.gender

如果用户同时提供了firstnamegender,那么您可以执行以下操作:

for record in list_of_records:
    if record.firstname == "John" and record.gender = "M":
        print "We found him!"
        print record.firstname, record.lastname, record.age, record.gender

此外,请务必关闭文件流,因此当您拨打open时,实际上是在打开文件流,因此在脚本结束时,请务必关闭它们,如此f.close() 。如果您使用with,则无需担心结束。

答案 1 :(得分:0)

对于更紧凑和灵活的解决方案,您可以使用标准库中的namedtuple类型:

import collections

record_tuple = collections.namedtuple('Record',
                      ['Firstname', 'Lastname', 'Age', 'Gender'])

n = raw_input("Enter %s :" % ' '.join('%s.%s' % (i, name) for i, name in enumerate(record_tuple._fields, 1)))
n = int(n)

StringSearch = raw_input('Enter %s :' % record_tuple._fields[n-1])

for line in open('abc'):
    record = record_tuple(*line.split())
    if record[n-1] == StringSearch:
        print ' '.join(record)

这样,您可以概括搜索代码。