首页 > 解决方案 > Sorting and enumerating imported data from txt file (Python)

问题描述

guys!

I'm trying to do a movie list, with data imported from a txt file that looks like this:

"Star Wars", "Y"
"Indiana Jones", "N"
"Pulp Fiction", "N"
"Fight Club", "Y"

(with Y = watched, and N = haven't seen yet)

I'm trying to sort the list by name, so that it'll look something like:

1. Fight Club (Watched)
2. Indiana Jones (Have Not Watched Yet)
3. Pulp Fiction (Have Not Watched Yet)
4. Star Wars (Watched)

And this is what I have so far:

def sortAlphabetically():
    movie_list = {}
    with open('movies.txt') as f:
        for line in f:
            movie, watched = line.strip().split(',')
            movie_list[movie.strip()] = watched.strip()
            if watched.strip() == '"N"':
                print(movie.strip() + " (Have Not Watched Yet)")
            if watched.strip() == '"Y"':
                print(movie.strip() + " (Watched)")

I found a tutorial and tried adding this code within the function to sort them:

sortedByKeyDict = sorted(movie_list.items(), key=lambda t: t[0])
    return sortedByKeyDict

I also tried using from ast import literal_eval to try and remove the quotation marks and then inserting this in the function:

        for k, v in movie_list.items():
            movie_list[literal_eval(k)] = v

But neither worked. What should I try next? Is it possible to remove the quotation marks? And how do I go about enumerating?

Thank you so much in advance!

标签: pythonpython-3.x

解决方案


给你,这应该这样做:

filename = './movies.txt'

watched_mapping = {
    'Y': 'Watched',
    'N': 'Have Not Watched Yet'
}

with open(filename) as f:
    content = f.readlines()

movies = []
for line in content:
    name, watched = line.strip().lstrip('"').rstrip('"').split('", "')
    movies.append({
        'name': name,
        'watched': watched
    })

sorted_movies = sorted(movies, key=lambda k: k['name'])

for i, movie in enumerate(sorted_movies, 1):
    print('{}. {} ({})'.format(
        i,
        movie['name'],
        watched_mapping[movie['watched']],
    ))

首先,我们定义watched_mapping哪些只是将文件中的值映射到要打印的值。

之后,我们打开文件并将其所有行读入一个content列表。

接下来要做的是解析该列表并从中提取值(我们必须从每一行中提取电影名称以及是否已观看)。我们会将这些值保存到另一个字典列表中,每个字典都包含电影名称以及是否已观看。

这就是name, watched = line.strip().lstrip('"').rstrip('"').split('", "')目的,它基本上从行的每一端剥离垃圾,然后在中间用垃圾分割行,返回干净namewatched.

接下来要做的是按name每个字典中的值对列表进行排序:

sorted_movies = sorted(movies, key=lambda k: k['name'])

之后,我们简单地枚举排序列表(从 1 开始)并解析它以打印出所需的输出(使用 watch_mapping 打印出句子而不是简单的Yand N)。

输出:

1. Fight Club (Watched)
2. Indiana Jones (Have Not Watched Yet)
3. Pulp Fiction (Have Not Watched Yet)
4. Star Wars (Watched)

不区分大小写的排序更改:

sorted_movies = sorted(movies, key=lambda k: k['name'].lower())

只需将电影排序的值更改为小写名称。现在在排序时,所有名称都被视为小写。


推荐阅读