簡體   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