我正在尝试弄清楚如何打开一个文件,然后使用Part no将它的内容存储到字典中。作为关键和其他信息作为价值。所以我希望它看起来像这样:
{Part no.: "Description,Price", 453: "Sperving_Bearing,9900", 1342: "Panametric_Fan,23400",9480: "Converter_Exchange,93859"}
我能够将文件中的文本存储到列表中,但我不确定如何为一个键分配多个值。我试图这样做而不导入任何模块。我一直在使用基本的str方法,列表方法和dict方法。
答案 0 :(得分:8)
对于像这样的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
并跳过前两行,然后继续正常运行。
答案 1 :(得分: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
答案 2 :(得分: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"))
答案 3 :(得分:-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:]
答案 4 :(得分:-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