我想要使用eval()函数将字符串转化为字典。按照网上的方法,我写了以下代码
with open(file, 'r+', encoding="utf-8") as f:
data_ = f.read()
data = eval(data_)
print(data_)
print(type(data))
但是,结果却是这样的:
<class 'set'>
并不是dict
怎么回事?
附件:源代码
from ui_word import Ui_word
from PySide2.QtWidgets import *
from PySide2.QtCore import *
import sys
class Word(QMainWindow, Ui_word):
def __init__(self):
super().__init__()
self.file = None
self.words = {}
self.word = ""
self.words_count = 0
self.setupUi(self)
self.show()
self.pb_file.clicked.connect(self.select_file)
self.a = None
self.b = None
self.data_ = None
self.data = None
def select_file(self):
file_path = QFileDialog.getOpenFileName(caption="选择文件", filter="(*.txt)")
if file_path[0]:
file = file_path[0]
self.lb_path.setText(file)
with open(file, 'r+', encoding="utf-8") as f:
data_ = f.read()
data = eval(data_)
print(data_)
print(type(data))
else:
QMessageBox.warning(self, "注意", "请重新选择文件")
def choose_tm(self):
self.a, self.b = random.choice(list(data.items()))
print(a, b)
if __name__ == "__main__":
app = QApplication()
window = Word()
sys.exit(app.exec_())