简体   繁体   English

如何读取元组的文本文件

[英]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我试过在用冒号分割时使用 tuple(value) 但它不能正常工作,因为我不知道如何分隔其他字符所以元组包含文本文件中的每个空格和引号。就像这样

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)它会显示为“伙伴关系”:('(', "'", 'p', 'o', 's', "'", ',', ' ', '1', '.', '字典中的 0', ')', '\n') 不是 '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() .由于值是简单的元组,我会考虑使用内置的ast模块并使用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:字典d将是:

{'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循环吗?

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.我能做的最好。 :-) :-)

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

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