简体   繁体   中英

return a list by reading a text file

I am reading a text file separated by space,the file looks like:

first line:hello 2928977 [1.2,9.7]

second line: apple 6723547 [8.2,3.1]

....

I want to return a list like[(hello,1.2,9.7),(apple,8.2,3.1),...] how do i do this? I know the first step is to set an empty list and then do

    output =[]
    inputfile = open('text.txt','r')
    for eachline in inputfile:
            l=line.strip()
            s=l.split(',')
            output.append((s[0],float(s[2][0]),float(s[2][1]))
    return output

but this doesn't work... it says invalid syntax....can someone help me? also I tried with another file with this method, but it says strings cannot be converted into float... i can't get this working, I would really appreaciate your help!Thanks!!!!!!!

Narrowly addressing the invalid syntax, count your parentheses, both open:

output.append((s[0],float(s[2][0]),float(s[2][1]))
             ^^          ^              ^

and close:

output.append((s[0],float(s[2][0]),float(s[2][1]))
                                 ^              ^^

See the problem? When you see a SyntaxError on a line where it makes no sense, look for mismatched parens, brackets, etc. that began on a previous line; the error usually occurs because the next line after the mismatch is being interpreted as part of the previous line, and of course it's not syntactically valid.

  1. split by ' ' instead of ','
  2. ast.literal_eval the string '[1.2,9.7]' to get a list [1.2,9.7]

from ast import literal_eval

output = []
with open('text.txt', 'r') as inputfile:
    for eachline in inputfile:
        l = eachline.strip()
        s = l.split(' ')
        ls = literal_eval(s[2])
        output.append((s[0], ls[0], ls[1]))
print(output)
# [('hello', 1.2, 9.7), ('apple', 8.2, 3.1)]

First, you should tell us invalid syntax happend in which line. It may cause by Tab or Space or something else.

Second, you can print s[2][0] and s[2][1] . I guess it may like this:

[8.2 and 3.1] , so it can not be converted into float.

You can modify it like this: output.append((s[0],float(s[2][0][1:]),float(s[2][1][:-1]))

Looks like you are trying to get tuple inside a list.

output_list = []

with open('answer.txt', 'r') as f:
    data = f.read().rstrip('\n')
    for line in data.split('\n'):
    line_updated = line.strip("[").strip(']').split(' ')
    required_elements = line_updated[0], line_updated[2]

    output_list.append(required_elements)

print('\n',output_list)

[('hello', '1.2,9.7'), ('apple', '8.2,3.1')]

I would usually use regex for this sort of pattern matching to make sure that the elements within [..] are numbers. But to continue with what you're doing:

#s='hello 2928977 [1.2,9.7]\napple 6723547 [8.2,3.1]\n'
#sp=s.splitlines()
with open(filename, "rb") as f:
    sp=f.readlines()

output=[]
for p in sp:
    words = p.split(" ")
    x,y=[float(x) for  x in words[2].strip("[|]").split(",")]
    output.append((words[0], x,y ) )
print(output)

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