[英]Python: List pulled from txt file as string not recognised as list
I saved the show data from the epguide API in a txt file, which looks like this:我将 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 '}] [{'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 '}]
When I now try to read it as a list in python it doesn't recognise it as such but only as a string despite the square brackets:当我现在尝试将其作为 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 remains a str and thus the search is also not working.类型仍然是 str ,因此搜索也不起作用。 How can I convert the data "back" to a list?
如何将数据“回”转换为列表?
One solution is as follows,一种解决方案如下,
with open('fileShows.txt', 'r', encoding='utf-8') as fs:
fs = fs.read()
print(type(fs))
my_list = list(fs)
print(type(my_list))
Another is,另一个是,
with open('fileShows.txt', 'r', encoding='utf-8') as fs:
fs = fs.read()
print(type(fs))
my_list = eval(fs)
print(type(my_list))
Basically eval() converts yours str retrieved from the file pointer to its base type which is of type list.基本上eval()将从文件指针中检索到的 str 转换为其类型列表的基本类型。
Try the following:请尝试以下操作:
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
Enjoy!享受!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.