想要将文本转成字典,文本形式如下:
'船舶', 96
'中港', 65
'事故', 41
'情况', 34
'安全', 32
'碰撞', 30
'该轮', 29
'水域', 28
with open('accident report_fenci_qutingyongci_cipin.txt') as f:
text=[]
for word in f.readlines():
temp=word.strip().split(',')
text.append(temp)
text=dict(text)
{"'船舶'": ' 96', "'中港'": ' 65', "'事故'": ' 41', "'情况'": ' 34', "'安全'": ' 32', "'碰撞'": ' 30', "'该轮'": ' 29', "'水域'": ' 28'}
{‘船舶’:96,‘中港’:65,‘事故’:41,……}
你题目的解答代码如下:
with open('accident report_fenci_qutingyongci_cipin.txt') as f:
text=[]
for word in f.readlines():
temp=word.strip().split(',')
temp[0] = temp[0][1:-1]
temp[1] = int(temp[1])
text.append(temp)
text=dict(text)
print(text)
如有帮助,望采纳!谢谢!
with open('accident report_fenci_qutingyongci_cipin.txt') as f:
text={}
for word in f.readlines():
temp=word.strip().split(',')
text[temp[0]]=int(temp[1])