简体   繁体   English

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

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

I have a .txt file that has names followed by numbers. 我有一个.txt文件,其名称后跟数字。 For Example 例如

namesToRatings = {}

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

Would output: 将输出:

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 

and so on... 等等...

How do I create a dictionary with the key being the name of the person and the value being a list of the numbers following that name? 如何创建一个字典,其中的键是人的名字,值是该名字后面的数字的列表?

Eg {Simon : [5, 0, 0, 0, 0,......... 5, 5, -5] 例如{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.

You can use a regex : 您可以使用正则表达式

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()

Try using the get_close_matches on the difference library. 尝试在差异库上使用get_close_matches。

Save the dictionary words and meanings in a JSON file, then it will be in the Form of a python dictionary. 将字典中的单词和含义保存在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)

You can add more exceptions here... 您可以在此处添加更多例外...

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}

This version is similar to the list based approach outlined in John's answer, but doesn't require reading the entire file into a list. 此版本类似于John的答案中概述的基于列表的方法,但不需要将整个文件读入列表。 The zip(*[lines]*2) will split the input (the lines) into pairs. zip(*[lines]*2)会将输入(各行)分成两对。 Output: 输出:

{
 '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