0

自己解决这个问题会非常令人欣慰,但我无法做到。

我想从包含字典形式数据的文本文件中获取随机值,例如:

{'One': '1111111', 'Two': '2222222', 'Three': '3333333'}

我尝试了一些变体,但代码目前是:

from random import *

table = open('file.txt')
random_value = random.choice(table.values())

当我尝试打印“random_value”(以查看它是否正常工作)时,出现错误:

AttributeError: 'file' object has no attribute 'values'
4

1 回答 1

1

table是一个文件对象,因此你想把它变成一个字典。这里我使用ast模块:

from random import choice # No need to import everything if you're going to use just one function
import ast
table = open('file.txt').read()
mydict = ast.literal_eval(table)
random_value = choice(mydict.values())
于 2013-04-05T07:45:14.563 回答