2

我试图弄清楚如何打开文件,然后使用零件号将其内容存储到字典中。作为键,其他信息作为值。所以我希望它看起来像这样:

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

我能够将文件中的文本存储到一个列表中,但我不确定如何为一个键分配多个值。我试图在不导入任何模块的情况下做到这一点。我一直在使用基本的 str 方法、list 方法和 dict 方法。

4

5 回答 5

9

对于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'}

----...你可以通过检查 if来摆脱这条线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代码中并跳过前两行,然后照常继续。

于 2013-07-21T18:12:28.967 回答
1

您可以将文件读入如下行列表:

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
于 2013-07-21T18:11:31.833 回答
0

这是我的尝试,在 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"))
于 2013-07-21T19:28:18.653 回答
-1

您应该将值存储为列表或元组。像这样的东西:

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:]
于 2013-07-21T18:10:57.797 回答
-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
于 2013-07-21T18:42:19.010 回答