"""__author__ = 余婷"""
"""
需求:播放指定歌曲的时候,给一个时间,能够把这首歌在这个时间对应的词返回
面向对象: 找一个类,让它拥有解析歌词的功能
"""
class Lyrics:
"""歌词类"""
def __init__(self, time='', word=''):
self._time = time
self.word = word
@property
def time(self):
return self._time
@time.setter
def time(self, value):
fen = float(value[1:3])
miao = float(value[4:])
self._time = fen*60+miao
def __gt__(self, other):
return self._time > other._time
def __repr__(self):
return str(self.__dict__)
class LyricsAnalysis:
"""歌词解析类"""
# name = ''
def __init__(self, name):
self.__name = name # 歌名
self.__all_lyric = [] # 保存当前歌名解析出来的歌词对象
# 分离歌词和时间
def __split_time_word(self, line):
# 时间 <-> 歌词
lines = line.split(']')
# print(lines)
# 获取每行的词
word = lines[-1]
# 遍历获取每一行的时间
for time in lines[:-1]:
# 根据时间和词创建歌词对象
ly_obj = Lyrics(word=word)
ly_obj.time = time
self.__all_lyric.append(ly_obj)
# 根据时间获取歌词
def get_lyric(self, time: int):
# 判断之前是否已经解析过
if self.__all_lyric:
print('~~~~~')
# 解析过,根据时间取值
for item in self.__all_lyric:
if item.time < time:
return item.word
# 没有解析过
# 读文件内容
try:
print('======')
with open('./files/'+self.__name+'.txt', 'r', encoding='utf-8') as f:
line = f.readline()
while line:
# print(line)
self.__split_time_word(line)
line = f.readline()
# __all_lyric保存了所有的歌词对象
self.__all_lyric.sort(reverse=True)
# print(self.__all_lyric)
# 根据时间取值
for item in self.__all_lyric:
if item.time < time:
return item.word
except FileNotFoundError:
print('没有响应的歌词')
# 蓝莲花 --> 蓝莲花数据 -->
ly_lan = LyricsAnalysis('蓝莲花')
print(ly_lan.get_lyric(10))
print(ly_lan.get_lyric(12))
print(ly_lan.get_lyric(20))
print(ly_lan.get_lyric(30))
# 七里香 --> 七里香数据 -->
# ly_qi = LyricsAnalysis('七里香')
网友评论