[英]How can I take a str/.txt input and make it into a list for pyton
I have a text file where the information that is formated as我有一个文本文件,其中的信息格式为
Title, Author, User Rating, Reviews, Price, Publication Year, Genre(Fiction or nonfiction)标题、作者、用户评分、评论、价格、出版年份、流派(小说或非小说)
sample data form txt样本数据表格txt
test_data = """
Girls,Hopscotch Girls,4.8,9737,7,2019,Non Fiction
I - Alex Cross,James Patterson,4.6,1320,7,2009,Fiction
If Animals Kissed Good Night,Ann Whitford Paul,4.8,16643,4,2019,Fiction
"""
They are all separated by a comma (,).它们都用逗号 (,) 分隔。 I wanted to take this input and make it into a list that looks something like
我想把这个输入变成一个看起来像的列表
list = {'Name': 'Girls','Author': 'Hopscotch Girls','User Rating':'4.8', 'Reviews':'9737', 'Price':'7', 'Publication Year':'2019', 'Genre':'Non Fiction'}
I'm trying to make it a list so its easier to look through because later on in my program since I want to be able to get user input like year and list all the books within the year with.我试图让它成为一个列表,以便更容易浏览,因为稍后在我的程序中,因为我希望能够获得像年份这样的用户输入并列出该年内的所有书籍。 It will also make formating an output easier.
它还将使格式化输出更容易。
If you are reading the data from a .txt file如果您从 .txt 文件中读取数据
data = {'Name': [], 'Author': [], 'User Rating': [], 'Reviews': [], 'Price': [], 'Publication Year': [], 'Genre': []}
with open("filename/goes/here.txt", "r") as f:
for line in f.readlines():
lineData = line.split(r",")
for key, ld in zip(data.keys(), lineData):
data[key].append(ld)
From your description I believe this is a solution.根据您的描述,我相信这是一个解决方案。 Some advice, never name your variables with the same name as any built-in functions.
一些建议,永远不要使用与任何内置函数相同的名称来命名变量。 (eg list, int, str)
(例如列表、整数、字符串)
Given your requirement鉴于您的要求
I'm trying to make it a list so its easier to look through because later on in my program since I want to be able to get user input like year and list all the books within the year with.
我试图让它成为一个列表,以便更容易浏览,因为稍后在我的程序中,因为我希望能够获得像年份这样的用户输入并列出该年内的所有书籍。 It will also make formating an output easier.
它还将使格式化输出更容易。
I think that a list of dictionaries would do the job.我认为字典列表可以完成这项工作。 Using list comprehension (I am using the test_data you defined in the question):
使用列表理解(我使用的是您在问题中定义的test_data ):
tags = ["Name", "Author", "User Rating", "Reviews", "Price", "Publication Year", "Genre"]
result = [dict(zip(tags, x.split(","))) for x in test_data.split("\n") if len(x.strip()) > 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.