Python:从字体格式的文本/文件创建字典 [英] Python: Create Dictionary from Text/File that's in Dictionary Format
问题描述
{'fawn':[1],'sermersheim':[3],'sonji ':[2],'scheuring':[2]}
正是这个,除了它包含125,000个条目。我可以使用read()读取文本文件,但是即使我使用
$ b初始化变量,它也会创建文件的文字文本的变量$ bdict = {}
您可以使用 eval
。例如,如果每个字典条目位于不同的行,这将会起作用:
dicts_from_file = []
打开('myfile.txt','r')as inf:
for inf in:
dicts_from_file.append(eval(line))
#dicts_from_file现在包含从文本创建的字典文件
或者,如果文件只是一个大字典(甚至在多行),您可以这个:
with open('myfile.txt','r')as inf:
dict_from_file = eval inf.read())
这可能是最简单的方法,但它不是最安全的。正如其他人在答案中提到的那样, eval
具有一些固有的安全隐患。如JBernardo所述,替代方案是使用 ast。 literal_eval
,它比eval更安全,因为它只会评估包含文字的字符串。在导入$ $ c $之后,您可以将 eval
中的所有调用替换为 ast.literal_eval
c> ast 模块。
如果你使用的是Python 2.4,那么你不会有 code>模块,您将不会
与
语句。代码会更像这样:
inf = open('myfile.txt','r')
dict_from_file = eval(inf.read())
inf.close()
不要再调用 inf.close()
。即使与
语句中的代码块引起异常,语句的美妙之处在于它们为您做, 。
I'd like to create a dictionary from a text file that I have, who's contents are in a 'dictionary' format. Here's a sample of what the file contains:
{'fawn': [1], 'sermersheim': [3], 'sonji': [2], 'scheuring': [2]}
It's exactly this except it contains 125,000 entries. I am able to read in the text file using read(), but it creates a variable of the literal text of the file even when I initialize the variable with
dict = {}
You can use the eval
built-in. For example, this would work if each dictionary entry is on a different line:
dicts_from_file = []
with open('myfile.txt','r') as inf:
for line in inf:
dicts_from_file.append(eval(line))
# dicts_from_file now contains the dictionaries created from the text file
Alternatively, if the file is just one big dictionary (even on multiple lines), you can do this:
with open('myfile.txt','r') as inf:
dict_from_file = eval(inf.read())
This is probably the most simple way to do it, but it's not the safest. As others mentioned in their answers, eval
has some inherent security risks. The alternative, as mentioned by JBernardo, is to use ast.literal_eval
which is much safer than eval since it will only evaluate strings which contain literals. You can simply replace all the calls to eval
in the above examples with ast.literal_eval
after importing the ast
module.
If you're using Python 2.4 you are not going to have the ast
module, and you're not going to have with
statements. The code will look more like this:
inf = open('myfile.txt','r')
dict_from_file = eval(inf.read())
inf.close()
Don't forget to call inf.close()
. The beauty of with
statements is they do it for you, even if the code block in the with
statement raises an exception.
这篇关于Python:从字体格式的文本/文件创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!