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,因此搜索也不起作用。如何将数据 "back" 转换为列表?
一种解决方案如下,
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
尽情享受吧!
我将 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,因此搜索也不起作用。如何将数据 "back" 转换为列表?
一种解决方案如下,
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
尽情享受吧!