簡體   English   中英

如何從文本文件讀取值並將其存儲到字典中。 [蟒蛇]

[英]How to read and store values from a text file into a dictionary. [python]

我試圖弄清楚如何打開文件,然后使用部件號將其內容存儲到字典中。 作為鍵,其他信息作為值。 所以我希望它看起來像這樣:

{Part no.: "Description,Price", 453: "Sperving_Bearing,9900", 1342: "Panametric_Fan,23400",9480: "Converter_Exchange,93859"}

我能夠將文件中的文本存儲到列表中,但是我不確定如何為一個鍵分配多個值。 我正在嘗試不導入任何模塊來執行此操作。 我一直在使用基本的str方法,list方法和dict方法。

對於這樣的txt文件

453     Sperving_Bearing    9900
1342    Panametric_Fan      23400
9480    Converter_Exchange  93859

你可以做

>>> newDict = {}
>>> with open('testFile.txt', 'r') as f:
        for line in f:
            splitLine = line.split()
            newDict[int(splitLine[0])] = ",".join(splitLine[1:])


>>> newDict
{9480: 'Converter_Exchange,93859', 453: 'Sperving_Bearing,9900', 1342: 'Panametric_Fan,23400'}

您只需檢查line.startswith('-----')是否可以擺脫----...行。

編輯 -如果您確定前兩行包含相同的內容,則可以

>>> testDict = {"Part no.": "Description,Price"}
>>> with open('testFile.txt', 'r') as f:
        _ = next(f)
        _ = next(f)
        for line in f:
            splitLine = line.split()
            testDict[int(splitLine[0])] = ",".join(splitLine[1:])       
>>> testDict
{9480: 'Converter_Exchange,93859', 'Part no.': 'Description,Price', 453: 'Sperving_Bearing,9900', 1342: 'Panametric_Fan,23400'}

這會將第一行添加到代碼中的testDict中,並跳過前兩行,然后繼續正常進行。

您可以將文件讀入以下行列表中:

lines = thetextfile.readlines()

您可以使用空格將一行分開:

items = somestring.split()

這是一個如何將列表存儲到字典中的原理示例:

>>>mylist = [1, 2, 3]
>>>mydict = {}
>>>mydict['hello'] = mylist
>>>mydict['world'] = [4,5,6]
>>>print(mydict)

諸如元組,列表和字典之類的容器可以彼此嵌套在一起作為它們的項。

要迭代列表,您必須使用for語句,如下所示:

for item in somelist:
    # do something with the item like printing it
    print item

這是我的刺刀,已在Python 2.x / 3.x上測試:

import re

def str2dict(filename="temp.txt"):
    results = {}
    with open(filename, "r") as cache:
        # read file into a list of lines
        lines = cache.readlines()
        # loop through lines
        for line in lines:
            # skip lines starting with "--".
            if not line.startswith("--"):
                # replace random amount of spaces (\s) with tab (\t),
                # strip the trailing return (\n), split into list using
                # "\t" as the split pattern
                line = re.sub("\s\s+", "\t", line).strip().split("\t")
                # use first item in list for the key, join remaining list items
                # with ", " for the value.
                results[line[0]] = ", ".join(line[1:])

    return results

print (str2dict("temp.txt"))

您應該將值存儲為列表或元組。 像這樣:

textname = input("ENter a file")
thetextfile = open(textname,'r')
print("The file has been successfully opened!")
thetextfile = thetextfile.read()
file_s = thetextfile.split()
holder = []
wordlist = {}
for c in file_s:
   wordlist[c.split()[0]] = c.split()[1:]

您的文件應如下所示:

Part no.;Description,Price
453;Sperving_Bearin,9900
1342;Panametric_Fan,23400
9480;Converter_Exchange,93859

比您只需要添加一些代碼:

d = collections.OrderedDict()
reader = csv.reader(open('your_file.txt','r'),delimiter=';')
d = {row[0]:row[1].strip() for row in reader}
for x,y in d.items():
     print x
     print y

暫無
暫無

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

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