简体   繁体   中英

How to extract info from a text file using a function. Python 3

'Have been up for ages so sorry if I'm not clear. Basically the task I have to do, like a query for databases I have there is an external text file which contains info. User will query for a criteria and I should be able to return with info.

For example:

Text file = 

RegNo **' Year'**

53245   **'3'** GH4P Richard Steel

35134 **'2'** G400A Anub Fankool

etc

So the 3 and 2 go under the Year header. I want to write a program were the user will input what year they want to retrieve.

For example Year 2 then it will retrieve the data: 35134 2 G400A Anub Fankool .

Need to do the same with Regno and name .

Just need to be pushed in the right direction so I can start/finish this.

Thanks.

code so far:

def order_name(regno, year, course, first_name, middle_name, last_name=None):
    if not last_name:
            last_name = middle_name
    else:
            first_name = "%s %s"  % (first_name, middle_name)
    return ("%s, %s" % (last_name, first_name), regno, course, year)
import re
s =""" 53245 3 GH4P Richard Steel\n35134 2 G400A Anub Fankool"""
x="2"
print re.findall(r"^(?=\d+\s+"+x+"\s+).*$",s,re.MULTILINE)

You can try something like this using re module.

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