简体   繁体   中英

How to read a text file for tuples

I have a text file of the form

plot:('neg', 0.4023264475292897)
derek:('pos', 0.5849625007211561)
is:('pos', 0.003209556475890097)
male:('pos', 0.49749965947081676)
model:('pos', 0.7004397181410923)

I'm trying to load this file into a dictionary of the form

{'plot':('neg', 0.4023264475292897), 'derek':('pos', 0.5849625007211561)}

with the key being a string and the tuple being string, float. I have tried using tuple(value) when splitting by the colon but it's not working properly as I don't know how to separate the other characters so the tuple includes every space and quote in the text file.Like so

def load_model(filepath):
dictionary = {}
with open(filepath, 'r') as textfile:
    for line in textfile:
        (key,value) = line.split(':')
        dictionary[key] = tuple(value)
return dictionary

it would show up as 'partnership': ('(', "'", 'p', 'o', 's', "'", ',', ' ', '1', '.', '0', ')', '\n') in the dictionary isntead of 'partenrship': ('pos', 1.0)

Any help would be appreciated, Thanks!

Since the values are simple tuples, I would consider using the built in ast module and parse them with literal_eval() .

import ast

with open(path) as f:
    d = {}
    for line in f:
        key, value = line.split(':')
        d[key] = ast.literal_eval(value)

The dictionary d will then be:

{'plot': ('neg', 0.4023264475292897),
 'derek': ('pos', 0.5849625007211561),
 'is': ('pos', 0.003209556475890097),
 'male': ('pos', 0.49749965947081676),
 'model': ('pos', 0.7004397181410923)}

If you're splitting by the colon, you get

x.split(':')[1] # ('key', val)

Since they are read as text, you can

1) Strip the leading and trailing brackets.
2) Split again on comma
3) Remove quotes on key, convert val to number
4) Pass both into a tuple.

Would this help you in that for loop?

for line in textfile:
    (key,value)=line.split(":")
    value2=value[1:-2].split(",")
    value2[0]=value2[0].replace("'","")
    value2[1]=float(value2[1])
    key=key.replace("'","")
    dictionary[key]=value

There maybe a simpler way (and indeed some of the commands here could be chained), but it's past midnight here; best I could do. :-)

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