[英]Python: Create Dictionary from Text/File that's in Dictionary Format
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]}
{'fawn':[1],'sermersheim':[3],'sonji':[2],'scheuring':[2]}
It's exactly this except it contains 125,000 entries. 除此之外,它包含125,000个条目。 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
我能够使用read()读取文本文件,但是即使我用变量初始化变量,它也会创建文件的文本文本的变量
dict = {}
dict = {}
You can use the eval
built-in. 您可以使用内置的
eval
。 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. 正如其他人在答案中提到的那样,
eval
存在一些固有的安全隐患。 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. JBernardo提到的替代方法是使用
ast.literal_eval
,它比eval更安全,因为它只会评估包含文字的字符串。 You can simply replace all the calls to eval
in the above examples with ast.literal_eval
after importing the ast
module. 在导入
ast
模块后,您可以使用ast.literal_eval
简单地将上述示例中对eval
所有调用替换为。
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. 如果你使用的是Python 2.4,你不会有
ast
模块,并且你不会有with
报表。 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()
. 别忘了打电话给
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. with
语句的优点是它们可以为您完成,即使with
语句中的代码块引发异常。
Using eval
might be dangerous. 使用
eval
可能很危险。 If json doesn't work, then I'd recommend using yaml which seems to work fine with your example input: 如果json不起作用,那么我建议使用yaml ,它似乎与你的示例输入一起正常工作:
>>> import yaml
>>> yaml.load("{'fawn': [1], 'sermersheim': [3], 'sonji': [2], 'scheuring': [2]}")
{'fawn': [1], 'scheuring': [2], 'sermersheim': [3], 'sonji': [2]}
It's not a production ready solution and may not work well with a file of your size, but if you need a simple way and can prepend you file to 它不是一个生产就绪的解决方案,可能不适合你的大小的文件,但如果你需要一个简单的方法,可以添加你的文件到
my_dict = {'fawn': [1], 'sermersheim': [3], 'sonji': [2], 'scheuring': [2]}
then you can rename it to a python file and simply import 然后你可以将它重命名为python文件,然后只需导入
from my_file import my_dict
I highly discourage using eval
though. 我强烈反对使用
eval
。 It may result in security issues if you don't have full control on the input file. 如果您没有对输入文件的完全控制,可能会导致安全问题。 Just import your dictionary and save them by using the
json
or pickle
module. 只需导入您的字典并使用
json
或pickle
模块保存它们。
This looks like json to me.
这对我来说就像是json。
Use the
json
module if so.
如果是这样,请使用
json
模块。
This looks like yaml to me. 这对我来说就像是yaml。 Use the pyyaml module if so.
如果是这样,请使用pyyaml模块 。 (As suggested by @jcollado).
(正如@jcollado所建议的那样)。
You can't use the json
module because it is strict about its input. 您不能使用
json
模块,因为它对输入很严格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.