如何获取str/.txt输入并将其放入pyton的列表中

2024-10-03 09:11:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,其中的信息格式为

标题、作者、用户评级、评论、价格、出版年份、流派(小说或非小说)

示例数据表单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
 """

它们都用逗号(,)分隔。我想把这个输入输入到一个类似

list = {'Name': 'Girls','Author': 'Hopscotch Girls','User Rating':'4.8', 'Reviews':'9737', 'Price':'7', 'Publication Year':'2019', 'Genre':'Non Fiction'}

我正试图把它列成一个列表,以便更容易查看,因为在我的程序后面,因为我希望能够获得用户输入,如年,并列出一年内的所有书籍。它还将使输出的格式化更容易


Tags: 数据用户标题示例评论价格作者小说
2条回答

如果您正在从.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)

根据你的描述,我相信这是一个解决方案。 一些建议是,不要用与任何内置函数相同的名称命名变量。(例如,列表、整数、str)

根据你的要求

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.

我想一份字典清单就行了。使用列表理解(我使用您在问题中定义的测试数据):

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]

相关问题 更多 >