简体   繁体   English

从 .txt 文件创建字典

[英]Creating a dictionary out of a .txt file

I am trying to create a python dictionary out of a txt file.我正在尝试从 txt 文件中创建一个 python 字典。 The thing is, some data is always getting lost during the process of conversion.问题是,一些数据在转换过程中总是会丢失。

I am trying to convert this file (its content) :我正在尝试转换此文件(其内容):

Tudo Bom;Static and Ben El Tavori;5:13;
I Gotta Feeling;The Black Eyed Peas;4:05;
Instrumental;Unknown;4:15;
Paradise;Coldplay;4:23;
Where is the love?;The Black Eyed Peas;4:13;

to a dictionary and always fail.到字典,总是失败。 Can you.你能。 please assist me ?请帮助我? My problem is that: cannot create a key-value pair for each line.我的问题是:无法为每一行创建一个键值对。

def get_songs():
    result = []
    with open('songs.txt', 'r') as songs:  # if the file is in the same name as script
        for song in songs: # Iterates through all lines in txt file.
            song.strip()  # Strips from endline symbol.
            data = song.split(';')  # Create list with elements separated by semicolon.
            result.append(  # Adds dict to the list of dicts.
                {
                    'name': data[0],  # Access splitted elements by their positions
                    'artist': data[1],
                    'length': data[2]
                }
            )

    return result  # Returns the list with dicts.


if __name__ == '__main__':
    print(get_songs())  # Prints out returned list.

Taking a guess at what the dictionary might look like, you could try something like this:猜测一下字典可能是什么样子,你可以尝试这样的事情:

data = {}

with open('songs.txt') as songs:
    for n, line in enumerate(songs, 1):
        song, artist, duration, *_ = line.split(';')
        data[f'song_{n}'] = {'song':song, 'artist': artist, 'duration': duration}

print(data)

Output:输出:

{'song_1': {'song': 'Tudo Bom', 'artist': 'Static and Ben El Tavori', 'duration': '5:13'}, 'song_2': {'song': 'I Gotta Feeling', 'artist': 'The Black Eyed Peas', 'duration': '4:05'}, 'song_3': {'song': 'Instrumental', 'artist': 'Unknown', 'duration': '4:15'}, 'song_4': {'song': 'Paradise', 'artist': 'Coldplay', 'duration': '4:23'}, 'song_5': {'song': 'Where is the love?', 'artist': 'The Black Eyed Peas', 'duration': '4:13'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM