从字典中提取歌手、歌名、音乐地址
时间: 2024-06-09 21:05:04 浏览: 5
对于提取歌手、歌名、音乐地址,可以采用正则表达式的方法。
假设我们有一个包含歌手、歌名、音乐地址的字典,格式为:
```python
music_dict = {
"song1": {
"singer": "singer1",
"url": "http://www.music.com/song1.mp3"
},
"song2": {
"singer": "singer2",
"url": "http://www.music.com/song2.mp3"
},
"song3": {
"singer": "singer3",
"url": "http://www.music.com/song3.mp3"
}
}
```
下面是提取歌手、歌名、音乐地址的代码:
```python
import re
for song, info in music_dict.items():
# 提取歌手
singer_pattern = re.compile(r'^(\w+)')
singer = singer_pattern.match(info['singer']).group(1)
# 提取歌名
song_pattern = re.compile(r'(\w+)\.\w+$')
song_name = song_pattern.match(song).group(1)
# 提取音乐地址
url = info['url']
print("歌手:", singer)
print("歌名:", song_name)
print("音乐地址:", url)
```
上述代码中,我们使用了正则表达式来提取歌手和歌名,其中 `^(\w+)` 匹配开头的单词,`(\w+)\.\w+$` 匹配文件名中的单词。对于音乐地址,我们直接从字典中取出即可。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)