编写一个歌曲信息管理系统(数据以文件的形式存储,提供文件的输入,输出、查找、替换及修改数据的功能)用函数的方法,模块化编写
时间: 2023-06-08 10:06:18 浏览: 49
好的,我会用Python语言编写一个歌曲信息管理系统,数据以文件的形式存储,并提供文件的输入、输出、查找、替换和修改数据的功能。
首先,我们要定义一个存储歌曲信息的类,包含歌曲的名称、歌手、专辑和年份等信息。然后,我们可以定义一些函数来处理这些数据,如读取、写入、查找、替换和修改操作。
以下是一个简单的代码示例,它能够帮助你开始:
```
#一个歌曲信息类
class Song:
def __init__(self, name, singer, album, year):
self.name = name
self.singer = singer
self.album = album
self.year = year
#将歌曲信息写入文件
def write_file(file_name, songs):
with open(file_name, 'w') as f:
for song in songs:
f.write('%s,%s,%s,%s\n' % (song.name, song.singer, song.album, song.year))
#从文件中读取歌曲信息
def read_file(file_name):
songs = []
with open(file_name, 'r') as f:
for line in f:
name, singer, album, year = line.strip().split(',')
songs.append(Song(name, singer, album, year))
return songs
#查找歌曲信息
def search_song(songs, keyword):
result = []
for song in songs:
if keyword in song.name or keyword in song.singer:
result.append(song)
return result
#替换歌曲信息
def replace_song(songs, old_song, new_song):
index = songs.index(old_song)
songs[index] = new_song
#修改歌曲信息
def modify_song(songs, song, new_info):
song.name = new_info[0]
song.singer = new_info[1]
song.album = new_info[2]
song.year = new_info[3]
#主函数
if __name__ == '__main__':
file_name = 'songs.txt'
songs = read_file(file_name)
print('Read data from file:', songs)
#新增一首歌曲
new_song = Song('青花瓷', '周杰伦', '我很忙', '2007')
songs.append(new_song)
write_file(file_name, songs)
print('After add:', read_file(file_name))
#查找一首歌曲
keyword = '旅行的意义'
result = search_song(songs, keyword)
print('Search "%s" result:' % keyword, result)
#替换一首歌曲
old_song = Song('七里香', '周杰伦', '七里香', '2004')
new_song = Song('不能说的秘密', '周杰伦', '不能说的秘密', '2007')
replace_song(songs, old_song, new_song)
write_file(file_name, songs)
print('After replace:', read_file(file_name))
#修改一首歌曲
song = Song('告白气球', '周杰伦', '周杰伦的床边故事', '2016')
new_info = ['夜曲', '周杰伦', '十一月的肖邦', '2005']
modify_song(songs, song, new_info)
write_file(file_name, songs)
print('After modify:', read_file(file_name))
```
在这个例子中,我们使用一个文件来存储歌曲信息,我们可以通过 read_file() 函数从文件中读取信息并返回一个歌曲信息的列表。然后,我们可以通过 write_file() 函数将歌曲信息写回文件。
我们还实现了 search_song() 函数来查找包含指定关键字的歌曲,replace_song() 函数来替换一首歌曲为另一首,以及 modify_song() 函数来修改一首歌曲的信息。
最后,我们通过主函数来测试这些功能,可以根据需要添加更多的功能和操作,或将代码封装成函数或模块以进行更好的可维护性。