简体   繁体   English

将文本文件读入字典

[英]Reading text file into dictionary

my text file has a format: 我的文本文件具有以下格式:

car,coche,auto
chair,silla,stuhl,sella

The first element is the english word. 第一个元素是英语单词。 I want to create a dictionary that does the following and returns dictionary. 我想创建一个执行以下操作并返回字典的字典。

dict =        {'coche'  : 'car',
               'auto'   : 'car',
               'stilla' : 'chair',
               'stuhl'  : 'chair',
               'sella'  : 'chair' }

I cannot use any built in function just loops and basic functions. 我不能使用任何内置函数,而只是循环和基本函数。

I know I want to: 我知道我想:

  • split the elements of each line 分割每行的元素
  • set the first item as the key 将第一项设置为关键
  • assign the second item as a value 将第二项分配为值
  • assign the following values to the same key 将以下值分配给同一键
    open_file = open(words_file_name, 'r')
    conversions = {}
    for line in open_file:
        piece = open_file.split(',')
        key = piece[0]
        conversions[key] = 0 
        if piece not in conversions:
            conversions[piece] = 1
        conversions[piece] += 1
    for key, value in conversions:
        return conversions

I have continuously gotten key errors, etc. 我不断遇到关键错误,等等。

Not tested but should work I think. 经过测试,但我认为应该可以。 Pop the first item, and use it as a value for all other words. 弹出第一项,并将其用作所有其他单词的值。

d = {}
with open('your-file.txt', 'r') as fhin:
    for line in fhin:
        words = line.strip().split(',')
        en_word = words.pop(0)
        for word in words:
            d[word] = en_word

You can just do this using dict.fromkeys 您可以使用dict.fromkeys来完成此操作

open_file = open(words_file_name, 'r')
conversions = {}
for line in open_file:
    val, keys = line.strip().split(',', 1)
    conversions.update(dict.fromkeys(keys.split(','), val))

print (conversions)

Output 产量

{'sella': 'chair', 'coche': 'car', 'stuhl': 'chair', 'silla': 'chair', 'auto': 'car'}

Your code is very close. 您的代码非常接近。 It just seems that you have key and value backwards. 似乎您的关键和价值倒退了。 The dictionary you are trying to create has the English word as the value and the non-English words as the keys of the dictionary. 您要创建的字典将英语单词作为值,将非英语单词作为字典的键。

open_file = open(words_file_name, 'r')
conversions = {}
for line in open_file:
    piece = line.split(',')
    value = piece[0]               # <- the first item will be the value
    for key in piece[1:]:          # <- iterate over the rest of the items in the line
        conversions[key] = value   # <- add the key:value pair to the dictionary
print(conversions)

simple loops: 简单循环:

open_file = open('read.txt', 'r')
conversions = {}
for line in open_file:
    piece = line.rstrip().split(',') #rstrip to remove \n
    key = piece[0]
    for obj in piece[1:]:
        conversions[obj]=key
print (conversions)

Output : 输出:

{'sella': 'chair', 'coche': 'car', 'stuhl': 'chair', 'silla': 'chair', 'auto': 'car'}

it looks like you have a csv. 看来您有csv。 You should try using csv.DictReader() from the csv module 您应该尝试从csv模块使用csv.DictReader()

import csv
csv_data=csv.DictReader(open('file_loc'))
for row in csv_data:
    #DoSomething  

this will make csv_data an OrderedDict , you can typecast it to Dict using dict(object) 这将使csv_data成为OrderedDict ,您可以使用dict(object)其类型转换为Dict。

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

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