繁体   English   中英

从此.txt文件创建字典{names:值列表}?

[英]Creating a dictionary {names : list of values} from this .txt file?

我有一个.txt文件,其名称后跟数字。 例如

namesToRatings = {}

with open("example.txt") as document:
    for line in document:
        print(line)

将输出:

Simon

5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 
0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5 

John

5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 
-3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0 

等等...

如何创建一个字典,其中的键是人的名字,值是该名字后面的数字的列表?

例如{Simon:[5,0,0,0,0,......... 5,5,-5]

with open("example.txt") as document:
    lines = [line for line in document if len(line.strip())]
    namesToRatings = {lines[i] : lines[i+1].split(" ") for i in range(0, len(lines), 2)}
    print(namesToRatings)  # print it, return it from a function, or set it as a global if you really must.

您可以使用正则表达式

import re

di={}
with open('file.txt') as f:
    for m in re.finditer(r'^([a-zA-Z]+)\s+([-\d\s]+)', f.read(), re.M):
        di[m.group(1)]=m.group(2).split()

尝试在差异库上使用get_close_matches。

将字典中的单词和含义保存在JSON文件中,然后以python字典的形式出现。

import json

from difflib import get_close_matches


data=json.load(open('filePath'))

def check_word(word) :
        word=word.lower()
         for word in data:
         return data
         If len(get_close_matches(word, data.keys(), cutoff=0.7))>0:
          return get_close_matches(word, data.keys(), cutoff=0.7)

您可以在此处添加更多例外...

with open("example.txt") as document:
    lines = (line.strip() for line in document)
    lines = (line for line in lines if line)
    pairs = zip(*[lines]*2)
    namesToRatings = {name: [int(x) for x in values.split()] for name, values in pairs}

此版本类似于John的答案中概述的基于列表的方法,但不需要将整个文件读入列表。 zip(*[lines]*2)会将输入(各行)分成两对。 输出:

{
 'Simon': [5, 0, 0, 0, 0, 0, 0, 1, 0, 1, -3, 5, 0, 0, 0, 5, 5, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 0, 1, 0, -5, 0, 0, 5, 5, 0, 5, 5, 5, 0, 5, 5, 0, 0, 0, 5, 5, 5, 5, -5], 
 'John': [5, 5, 0, 0, 0, 0, 3, 0, 0, 1, 0, 5, 3, 0, 5, 0, 3, 3, 5, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 3, 5, 0, 0, 0, 0, 0, 5, -3, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 5, 5, 0, 3, 0, 0]
}

暂无
暂无

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

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