Reading from a text file

I need to read from a text file a first name, last name, then 12 scores. This needs to be returned from a function as a tuple. I have figured out how to assign the individual characters into a tuple, is there a way to put each word in the text file into a tuple? Here is the format of the text file:
Last name First name x x x x x x x x x x x
Last name First name x x x x x x x x x x x

Comments

  • [b][red]This message was edited by Moderator at 2004-12-8 12:30:16[/red][/b][hr]
    : I need to read from a text file a first name, last name, then 12 scores. This needs to be returned from a function as a tuple. I have figured out how to assign the individual characters into a tuple, is there a way to put each word in the text file into a tuple? Here is the format of the text file:
    : Last name First name x x x x x x x x x x x
    : Last name First name x x x x x x x x x x x

    Here's a simple example of how to turn your file into tuples:

    [code]
    for line in file('scores.txt'):
    if line.strip():
    print tuple(line.strip().split())
    [/code]

    Or, if you have Python 2.4, you can use a generator expression to only perform the .strip() call once per line:

    [code]
    for line in (line.strip() for line in file('scores.txt')):
    if line:
    print tuple(line.split())
    [/code]

    Or, just use an intermediate step:

    [code]
    for line in file('scores.txt'):
    stripped = line.strip()
    if stripped:
    print tuple(stripped.split())
    [/code]

    In case you didn't know, an empty string is "false" and any other string is "true" in terms of an "if" statement.

    [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

    [code]
    $ select * from users where clue > 0
    no rows returned
    [/code]



  • [b][red]This message was edited by OneBig40 at 2004-12-8 13:47:18[/red][/b][hr]
    [b][red]This message was edited by OneBig40 at 2004-12-8 13:33:35[/red][/b][hr]
    I need a way to group all of the tuples created into a list and return it through the function. The only thing i can get it to do is make seperate lists but i need one.

    never mind I figured it out. Thanks to infidel for the help earlier though

    [code]
    def return_scores(rfile):
    scorelist = []
    for line in rfile:
    if line.strip():
    scores = tuple(line.strip().split())
    scorelist.append(scores)
    global scorelist
    return scorelist
  • [b][red]This message was edited by Moderator at 2004-12-8 14:34:29[/red][/b][hr]
    [b][red]This message was edited by Moderator at 2004-12-8 14:34:10[/red][/b][hr]
    : never mind I figured it out. Thanks to infidel for the help earlier though
    :
    : [code]
    : def return_scores(rfile):
    : scorelist = []
    : for line in rfile:
    : if line.strip():
    : scores = tuple(line.strip().split())
    : scorelist.append(scores)
    : global scorelist
    : return scorelist
    [/code]

    You don't need "global scorelist" there. Just return it.


    [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

    [code]
    $ select * from users where clue > 0
    no rows returned
    [/code]





  • Apparently i was confused because what i really need to do was group the info from the text into seperate tuples like this:
    (Last name,first name),(x,x,x,x,x),(x,x,x,x),(x,x),(x)
    then from there create a list of tuples where each of the above five tuples is one big tuple (ie):
    [((Last name,first name),(x,x,x,x,x),(x,x,x,x),(x,x),(x)),
    ((Last name,first name),(x,x,x,x,x),(x,x,x,x),(x,x),(x)),
    ((Last name,first name),(x,x,x,x,x),(x,x,x,x),(x,x),(x))]
    This is the code i have so far:
    [code]
    def return_scores(rfile):
    """returns a list scores as tuples"""
    scorelist = []
    name = ()
    hw = ()
    proj = ()
    tests = ()
    final = ()
    for line in rfile:
    if line.strip():
    scores = tuple(line.strip().split())
    name += tuple(scores[0:2])
    hw +=tuple(scores[2:7])
    proj +=tuple(scores[7:11])
    tests +=tuple(scores[11:13])
    final +=tuple(scores[12:13])
    student_tuple = ()
    student_tuple += ((name)+(hw)+(proj)+(tests)+(final))
    scorelist.append(student_tuple)
    name = ()
    hw = ()
    proj =()
    tests = ()
    final = ()
  • : Apparently i was confused because what i really need to do was group the info from the text into seperate tuples like this:
    : (Last name,first name),(x,x,x,x,x),(x,x,x,x),(x,x),(x)
    : then from there create a list of tuples where each of the above five tuples is one big tuple (ie):
    : [((Last name,first name),(x,x,x,x,x),(x,x,x,x),(x,x),(x)),
    : ((Last name,first name),(x,x,x,x,x),(x,x,x,x),(x,x),(x)),
    : ((Last name,first name),(x,x,x,x,x),(x,x,x,x),(x,x),(x))]
    : This is the code i have so far:
    : [code]
    : def return_scores(rfile):
    : """returns a list scores as tuples"""
    : scorelist = []
    : name = ()
    : hw = ()
    : proj = ()
    : tests = ()
    : final = ()
    : for line in rfile:
    : if line.strip():
    : scores = tuple(line.strip().split())
    : name += tuple(scores[0:2])
    : hw +=tuple(scores[2:7])
    : proj +=tuple(scores[7:11])
    : tests +=tuple(scores[11:13])
    : final +=tuple(scores[12:13])
    : student_tuple = ()
    : student_tuple += ((name)+(hw)+(proj)+(tests)+(final))
    : scorelist.append(student_tuple)
    : name = ()
    : hw = ()
    : proj =()
    : tests = ()
    : final = ()
    [/code]

    Interesting. There's a few changes I would make. First, in many cases there's no need to bother declaring/initializing/re-initializing your variables in Python. Furthermore, sometimes you don't even need the variables at all. Here's what I mean:

    [code]
    from pprint import pprint

    def xscores(f):
    for line in file(f):
    items = tuple(line.strip().split())
    if len(items) == 14:
    yield (
    tuple(items[0:2]),
    tuple(items[2:7]),
    tuple(items[7:11]),
    tuple(items[11:13]),
    tuple(items[13:14])
    )

    def return_scores(f):
    return list(xscores(f))

    pprint(return_scores('scores.txt'))
    [/code]

    I also, just for fun, made the xscores function a generator. What this means is that you can use it in 'for' loops and it will only return (yield) one return value at a time instead of building up the entire list and then returning it.

    [code]
    >>> for score in xscores('scores.txt'):
    ... pprint(score)
    ...
    (('John', 'Smith'),
    ('1', '2', '3', '4', '5'),
    ('6', '7', '8', '9'),
    ('10', '11'),
    ('12',))
    (('Jane', 'Doe'),
    ('12', '11', '10', '9', '8'),
    ('7', '6', '5', '4'),
    ('3', '2'),
    ('1',))
    >>>
    [/code]

    Generators are especially useful if you're processing large amounts of data, but they're kind of neat anyways. You can turn a generator result into a full list by using the list() constructor (as in my return_scores() function above).


    [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

    [code]
    $ select * from users where clue > 0
    no rows returned
    [/code]

  • How do convert a float ie: 3.33333333333333
    to a specified number of decimal places ie: 3.33
  • : How do convert a float ie: 3.33333333333333
    : to a specified number of decimal places ie: 3.33

    You can use string formatting. If you've ever used printf() in C it's kind of like that. You create a string that has placeholders in it, and then you use the % operator to send values to those placeholders.

    Try these:
    [code]
    >>> "%s=%s" % ('foo', 2)
    'foo=2'
    >>> "%d==%d" % (1, 2)
    '1==2'
    >>> "%d==%2d" % (1, 2)
    '1== 2'
    >>> "f = %f" % (3.333333333)
    'f = 3.333333'
    >>> "f = %.2f" % (3.333333333)
    'f = 3.33'
    [/code]

    Bear in mind these only return a string representation of the number, not a number. If you're actually trying to round off the number to a fixed set of decimal places then that is something else entirely.


    [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

    [code]
    $ select * from users where clue > 0
    no rows returned
    [/code]

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories