青栀初夏 2021-12-09 23:51 采纳率: 50%
浏览 39
已结题

python中如何将文本转成字典

问题遇到的现象和发生背景

想要将文本转成字典,文本形式如下:
'船舶', 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,……}

  • 写回答

2条回答 默认 最新

  • 关注

    你题目的解答代码如下:

    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)
    

    img

    如有帮助,望采纳!谢谢!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 12月18日
  • 已采纳回答 12月10日
  • 创建了问题 12月9日