【问题标题】:Python: List pulled from txt file as string not recognised as listPython:从txt文件中提取的列表作为字符串不被识别为列表
【发布时间】:2020-04-02 05:16:28
【问题描述】:

我将来自 epguide API 的节目数据保存在一个 txt 文件中,如下所示:

[{'epguide_name': 'gooddoctor', 'title': '好医生', 'imdb_id': 'tt6470478', 'episodes': 'http://epguides.frecar.no/show/gooddoctor/', 'first_episode': 'http://epguides.frecar.no/show/gooddoctor/first/' , 'next_episode': 'http://epguides.frecar.no/show/gooddoctor/next/', 'last_episode': 'http://epguides.frecar.no/show/gooddoctor/last/', 'epguides_url': 'http://www.epguides.com/gooddoctor'}]

当我现在尝试在 python 中将其读取为列表时,它不会将其识别为这样,而只是将其识别为字符串,尽管有方括号:

    with open(file_shows, 'r', encoding='utf-8') as fs:
       fs = fs.read()
       print(type(fs))
       print(next((item for item in list if item['title'] == show), None)['episodes'])

Type 仍然是 str,因此搜索也不起作用。如何将数据“返回”到列表?

【问题讨论】:

  • 您使用fs.read() 阅读的任何内容都会以字符串形式返回。它不会尝试解析为 Python 表达式。
  • 谢谢汤姆,还有其他选择吗?

标签: python string list square-bracket


【解决方案1】:

一种解决方法如下,

with open('fileShows.txt', 'r', encoding='utf-8') as fs:
    fs = fs.read()
    print(type(fs))
    my_list = list(fs)
    print(type(my_list))

另一个是,

with open('fileShows.txt', 'r', encoding='utf-8') as fs:
    fs = fs.read()
    print(type(fs))
    my_list = eval(fs)
    print(type(my_list))

基本上 eval() 将从文件指针中检索到的 str 转换为其基本类型,即 list 类型。

【讨论】:

    【解决方案2】:

    尝试以下方法:

    import json
    with open(file_shows, 'r', encoding='utf-8') as fs:
           data = json.loads(fs.read().replace("'",'"')) # data will be list and not str
    

    享受吧!

    【讨论】:

    • 嗨,Gabip,感谢您的回复。我试过 json.loads()。它给了我以下错误:'TypeError: JSON object must be str, bytes or bytearray, not TextIOWrapper' 这很奇怪,因为类型 fs 是 .
    • 已更新我的解决方案,请立即尝试 :)
    • 嗨,Gabip,你太棒了。谢谢你还在努力!!我再次编写了一个快速文件来测试您的新解决方案,因为我很想知道它是否有效。不幸的是,现在我收到了这个错误:'json.decoder.JSONDecodeError:期望用双引号括起来的属性名称:第 1 行第 3 列(字符 2)'。 Arpit 的 eval() 解决方案虽然有效。
    • @dizcotec 不幸的是我的解决方案在这里不起作用。我没有注意到您的 json 元素是用单引号而不是双引号引起来的,这会导致您的 json 无效,因此 json 模块无法解析它。如果你用 fs.read().replace("'",'"') 将所有单引号替换为双引号,它会起作用,但在你的情况下,我想使用 eval 会更好。无论如何,如果您想尝试一下,我已经再次更新了我的解决方案(我在我的机器上检查过,效果很好)。
    猜你喜欢
    • 1970-01-01
    • 2018-08-02
    • 2012-05-04
    • 2014-05-02
    • 2016-05-14
    • 2018-12-13
    • 1970-01-01
    • 2021-03-08
    • 2020-03-27
    相关资源
    最近更新 更多