簡體   English   中英

Python:從txt文件中提取的列表作為字符串未被識別為列表

[英]Python: List pulled from txt file as string not recognised as list

我將 epguide API 的顯示數據保存在一個 txt 文件中,如下所示:

[{'epguide_name': 'gooddoctor', 'title': 'The Good Doctor', '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'])

類型仍然是 str ,因此搜索也不起作用。 如何將數據“回”轉換為列表?

一種解決方案如下,

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 轉換為其類型列表的基本類型。

請嘗試以下操作:

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

享受!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM