如何读取文本文件中的值并将其存储到字典中。[Python]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17775273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read and store values from a text file into a dictionary. [python]
提问by Harry Harry
I'm trying to figure out how to open up a file and then store it's contents into a dictionary using the Part no. as the key and the other information as the value. So I want it to look something like this:
我试图弄清楚如何打开一个文件,然后使用部件号将其内容存储到字典中。作为键,其他信息作为值。所以我希望它看起来像这样:
{Part no.: "Description,Price", 453: "Sperving_Bearing,9900", 1342: "Panametric_Fan,23400",9480: "Converter_Exchange,93859"}
I was able to store the text from the file into a list, but I'm not sure how to assign more than one value to a key. I'm trying to do this without importing any modules. I've been using the basic str methods, list methods and dict methods.
我能够将文件中的文本存储到列表中,但我不确定如何为一个键分配多个值。我正在尝试在不导入任何模块的情况下执行此操作。我一直在使用基本的 str 方法、list 方法和 dict 方法。
采纳答案by Sukrit Kalra
For a txt
file like so
对于这样的txt
文件
453 Sperving_Bearing 9900
1342 Panametric_Fan 23400
9480 Converter_Exchange 93859
You can just do
你可以做
>>> 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'}
You can get rid of the ----...
line by just checking if line.startswith('-----')
.
您可以----...
通过检查 if来摆脱该行line.startswith('-----')
。
EDIT- If you are sure that the first two lines contain the same stuff, then you can just do
编辑- 如果您确定前两行包含相同的内容,那么您可以这样做
>>> 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'}
This adds the first line to the testDict
in the code and skips the first two lines and then continues on as normal.
这将第一行添加到testDict
代码中并跳过前两行,然后继续正常运行。
回答by Tiago
You should store the values as a list or a tuple. Something like this:
您应该将值存储为列表或元组。像这样的东西:
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:]
回答by nio
You can read a file into a list of lines like this:
您可以将文件读入如下所示的行列表:
lines = thetextfile.readlines()
You can split a single line by spaces using:
您可以使用以下方法按空格拆分单行:
items = somestring.split()
Here's a principial example how to store a list into a dictionary:
这是一个如何将列表存储到字典中的主要示例:
>>>mylist = [1, 2, 3]
>>>mydict = {}
>>>mydict['hello'] = mylist
>>>mydict['world'] = [4,5,6]
>>>print(mydict)
Containers like a tuple, list and dictionary can be nested into each other as their items.
像元组、列表和字典这样的容器可以作为它们的项相互嵌套。
To itereate a list you have to use a for statement like this:
要迭代一个列表,你必须使用这样的 for 语句:
for item in somelist:
# do something with the item like printing it
print item
回答by Michael
Your file should look like this:
您的文件应如下所示:
Part no.;Description,Price
453;Sperving_Bearin,9900
1342;Panametric_Fan,23400
9480;Converter_Exchange,93859
Than you just need to add a bit of code:
比你只需要添加一些代码:
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
回答by AWainb
Here's my stab at it, tested on Python 2.x/3.x:
这是我的尝试,在 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"))