简体   繁体   English

从文本将键和值读取到python dict中

[英]reading key and values into python dict from text

I have a text file in this format. 我有这种格式的文本文件。

the 0.418 0.24968 -0.41242 0.1217 0.34527 -0.044457 -0.49688 -0.17862 -0.00066023 -0.6566 0.27843 -0.14767 -0.55677 0.14658 -0.0095095 0.011658
and 0.26818 0.14346 -0.27877 0.016257 0.11384 0.69923 -0.51332 -0.47368 -0.33075 -0.13834 0.2702 0.30938 -0.45012 -0.4127 -0.09932 0.038085 

I want to read it into a python dict variable such that I have 我想将其读入python dict变量中,以便

{'the': [0.418, 0.24968,..], 'and': [0.26818 0.14346,..]}

I am not sure how to start? 我不确定如何开始?

You can iterate over the file line by line. 您可以逐行遍历文件。 Then split on whitespace, use the index [0] as the key, then use a list comprehension to convert the remaining values to a list of float . 然后在空白处split ,使用索引[0]作为键,然后使用列表推导将其余值转换为float列表。

with open(text_file) as f:
    d = dict()
    for line in f:
        data = line.split()
        d[data[0]] = [float(i) for i in data[1:]]
    print(d)

Output 产量

{'and': [0.26818, 0.14346, -0.27877, 0.016257, 0.11384, 0.69923, -0.51332, -0.47368, -0.33075, -0.13834, 0.2702, 0.30938, -0.45012, -0.4127, -0.09932, 0.038085],
 'the': [0.418, 0.24968, -0.41242, 0.1217, 0.34527, -0.044457, -0.49688, -0.17862, -0.00066023, -0.6566, 0.27843, -0.14767, -0.55677, 0.14658, -0.0095095, 0.011658]}

Here's a solution that works: 这是一个可行的解决方案:

my_dict = {}
with open('your_file_name') as f:
    for line in f:
        elements = line.split()
        my_dict[elements[0]] = [float(e) for e in elements[1:]]

Note that the solution suggested by @CoryKramer uses readlines , which returns a list and not an iterator. 请注意,@ CoryKramer建议的解决方案使用readlines ,它返回一个列表,而不是迭代器。 So I would not recommend using his solution for large files (it will take too much memory unnecessarily). 因此,我不建议将他的解决方案用于大文件(不必要地占用太多内存)。

Is this a start? 这是一个开始吗?

import json

variable_one = "the 0.418 0.24968 -0.41242 0.1217 0.34527 -0.044457 -0.49688 -0.17862 -0.00066023 -0.6566 0.27843 -0.14767 -0.55677 0.14658 -0.0095095 0.011658"

variable_one = variable_one.split()
json_variable_one = []
json_variable_one = variable_one[0], variable_one[1:]

print(json.dumps(json_variable_one))

output: 输出:

["the", ["0.418", "0.24968", "-0.41242", "0.1217", "0.34527", "-0.044457", "-0.49688", "-0.17862", "-0.00066023", "-0.6566", "0.27843", "-0.14767", "-0.55677", "0.14658", "-0.0095095", "0.011658"]] [“ the”,[“ 0.418”,“ 0.24968”,“-0.41242”,“ 0.1217”,“ 0.34527”,“-0.044457”,“-0.49688”,“-0.17862”,“-0.00066023”,“-0.6566” ”,“ 0.27843”,“-0.14767”,“-0.55677”,“ 0.14658”,“-0.0095095”,“ 0.011658”]]

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

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