简体   繁体   English

元组的字符串参数-python

[英]string argument to tuple - python

I have opened a text file and printed it out. 我打开了一个文本文件并打印了出来。 I am trying to allow the user to input details(first name or department name 'CSEE') of the line they would like to print in tuple's in this order: 我试图允许用户按以下顺序输入要在元组中打印的行的详细信息(名字或部门名称'CSEE'):

 Timothy, Johnson      12345 Law      £25000

This is the code I have so far. 这是我到目前为止的代码。

fob=open('c:/Users/username/Desktop/CE151 Python/ass2/info.txt','r')
print("enter student file name: )")
text_file = open("info.txt","r")
for item in fob:
    for y in item:
        item.split(' ')
        print(item)
        break
find = input('Input Details: ')
for find in item:
    print(find)

the info.txt file contains: info.txt文件包含:

12345 Law 35000 Bob Liam
12346 Biology 25000 Tom Hanks
12350 Economics 30000 Billy Kid
13123 Economics 55000 Finn Balor
13124 Maths 40000 David Young
13126 Physics 25000 John Wayne Smith
13127 History 35000 Tony Gregg
13128 History 27500 Lily Joe
13129 Chemistry 25000 Saxton Crown
13130 Law 22000 jimmy Arrow

I want the user to input information, for example if the user inputs History, then the all the people studying history will be printed 我希望用户输入信息,例如,如果用户输入“历史记录”,那么将打印所有学习历史记录的人

It seems like your task is pretty simple - simply to open a file, and then for each line read some space separated data from it, and rearrange it. 看来您的任务很简单-只需打开一个文件,然后为每一行读取一些与它分隔的数据,然后重新排列。 This can be done very concisely in Python. 这可以在Python中非常简洁地完成。 I'm not quite sure why you have so many input s, I think you'll need at most one, if you want the user to be able to enter the file name interactively. 我不太确定为什么会有这么多input ,如果您希望用户能够以交互方式输入文件名,那么我最多只需要一个。 Here is my code: 这是我的代码:

#open the file
with open("input.txt") as student_file:
    #for each line
    for line in student_file:
        #read some space separated data and rearrange it
        print("{3}, {4}\t{0}\t{1}\t£{2}".format(*line.split()))

Where input.txt has your input, this leads to the output input.txt有您的输入的地方,这会导致输出

Bob, Liam   12345   Law £35000
Tom, Hanks  12346   Biology £25000
Billy, Kid  12350   Economics   £30000
Finn, Balor 13123   Economics   £55000
David, Young    13124   Maths   £40000
John, Wayne 13126   Physics £25000
Tony, Gregg 13127   History £35000
Lily, Joe   13128   History £27500
Saxton, Crown   13129   Chemistry   £25000
jimmy, Arrow    13130   Law £22000

This output has been tab separated, which seemed close to what you wanted. 此输出已制表符分隔,似乎接近您想要的输出。 If you want it to be space separated again, you can replace the \\t s with spaces. 如果希望再次将它们分隔开,则可以用空格替换\\t If you want it to be space separated but still aligned, this might take some more work. 如果您希望将其分隔开但仍对齐,则可能需要更多的工作。

Updating the code to suit your new requirement, I think: 我认为更新代码以适应您的新要求:

target_course = input("which course should be filtered by? ")
with open("input.txt") as student_file:
    for line in student_file:
        data = line.split()
        if data[1] == target_course:
            print("{3}, {4}\t{0}\t{1}\t£{2}".format(*data))

Example of it in action: 它的作用示例:

which course should be filtered by? History
Tony, Gregg 13127   History £35000
Lily, Joe   13128   History £27500

If the idea is for them to filter by whatever field they like, this might get a little more complicated. 如果想法是让他们根据自己喜欢的任何字段进行过滤,则可能会变得更加复杂。 I would use a namedtuple , and check with that. 我将使用namedtuple ,并进行检查。 This can be done like below: 可以像下面这样完成:

from collections import namedtuple

fields = ["forename", "surname", "id", "subject", "cost"]

Row = namedtuple("Row", fields)

target_field = input("what field do you want to filter by (one of {})? ".format(fields))
target_value = input("what value do you want to filter by? ")

with open("input.txt") as student_file:
    for line in student_file:
        id_, subject, cost, forename, *surname = line.split()
        data = Row(id=id_, subject=subject, cost=cost, forename=forename, surname=" ".join(surname))
        if getattr(data, target_field) == target_value:
            print("{0.surname}, {0.forename}\t{0.id}\t{0.subject}\t£{0.cost}".format(data))

Along with this refactoring, the code may have become a little clearer. 伴随着这种重构,代码可能变得更加清晰了。 Note that I've fixed a bug I actually realised it had previously - it couldn't handle multiple word surnames. 请注意,我已经修复了一个我以前真正意识到的错误-它无法处理多个单词的姓氏。 Embarassing especially as multiple word surnames and the handling thereof are very close to my heart. 尤其是因为多个单词的姓氏及其处理方式使我非常感动。 It now works as follows: 现在,它的工作方式如下:

what field do you want to filter by (one of ['forename', 'surname', 'id', 'subject', 'cost'])? subject
what value do you want to filter by? History
Gregg, Tony 13127   History £35000
Joe, Lily   13128   History £27500

what field do you want to filter by (one of ['forename', 'surname', 'id', 'subject', 'cost'])? cost
what value do you want to filter by? 25000
Hanks, Tom  12346   Biology £25000
Wayne Smith, John   13126   Physics £25000
Crown, Saxton   13129   Chemistry   £25000

Note that it's not very sophisticated yet - it doesn't do any input validation, for example, and cost is given as an integer not prefixed by a £. 请注意,它还不是很复杂-例如,它不进行任何输入验证,并且cost以不带£前缀的整数形式给出。 This is something you can try to add to the program. 您可以尝试将其添加到程序中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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