簡體   English   中英

將文本文件讀入字典

[英]Reading text file into dictionary

我的文本文件具有以下格式:

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

第一個元素是英語單詞。 我想創建一個執行以下操作並返回字典的字典。

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

我不能使用任何內置函數,而只是循環和基本函數。

我知道我想:

  • 分割每行的元素
  • 將第一項設置為關鍵
  • 將第二項分配為值
  • 將以下值分配給同一鍵
    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

我不斷遇到關鍵錯誤,等等。

經過測試,但我認為應該可以。 彈出第一項,並將其用作所有其他單詞的值。

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

您可以使用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)

產量

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

您的代碼非常接近。 似乎您的關鍵和價值倒退了。 您要創建的字典將英語單詞作為值,將非英語單詞作為字典的鍵。

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)

簡單循環:

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)

輸出:

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

看來您有csv。 您應該嘗試從csv模塊使用csv.DictReader()

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

這將使csv_data成為OrderedDict ,您可以使用dict(object)其類型轉換為Dict。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM