Python 使用正则表达式仅提取艺术家名称

Python 使用正则表达式仅提取艺术家名称,python,regex,Python,Regex,我正在做一个将youtube播放列表转换为spotify播放列表的项目。我已经使用youtube api获取歌曲标题,使用spotify playlist在播放列表中添加歌曲 问题是我必须从像《Zedd&Kehlani-Good Thing》(官方音乐视频)这样的标题中获取艺术家姓名和曲目名称。我尝试使用youtube dlextract metadata方法来实现这一点,但它似乎大部分时间都不起作用。幸运的是,我发现了一个模块,其中提供了艺术家和曲目名称,但如果标题中提到了艺术家,则还会返回多

我正在做一个将youtube播放列表转换为spotify播放列表的项目。我已经使用youtube api获取歌曲标题,使用spotify playlist在播放列表中添加歌曲

问题是我必须从像《Zedd&Kehlani-Good Thing》(官方音乐视频)这样的标题中获取艺术家姓名和曲目名称。我尝试使用
youtube dl
extract metadata方法来实现这一点,但它似乎大部分时间都不起作用。幸运的是,我发现了一个模块,其中提供了艺术家和曲目名称,但如果标题中提到了艺术家,则还会返回多个艺术家。但我只能在spotify上搜索一个艺术家的名字

因此,我需要帮助找到一个正则表达式,如果字符串中存在多个艺术家,它将只返回一个艺术家。 我想出了这个正则表达式-

artist_pattern = re.compile(r'([\w-]+\s?[\w]*)\s?([\w\s]+)?')

matches = artist_pattern.finditer(names)

for match in matches :
    print(match.group(1))
这在某些情况下非常有效,但如果
name=ABC feat,则会失败。XYZ
打印出ABC featXYZ

我知道在网上阅读正则表达式很难(特别是像我这样的初学者写的),所以我会尽力解释-

[\w-]+ ##matches chars and - for artist name
\s?  ## if the artist has a space between his name (eg - DJ Snake) ***this is where i think this regex fails***
[\w]* ## if the artist name has a space this will record the chars after the space
\s ## a space if the title has more than one artist
 ([\w\s]+)? ## if the title has more than one artist this will record the left artists
正如我前面提到的,这不适用于像这样的测试用例-

Anne-Marie & James Arthur ## result - Anne-Marie James Arthur
Calvin Harris, Rag'n'Bone Man ##result - Calvin HarrisnBone Man
DJ Snake feat. J Balvin ## result - DJ SnakeJ Balvin
和类似的测试用例

现在我知道我可以在正则表达式中明确提到这些符号(
&
专长
英尺
),但这个解决方案只适用于一些标题。如果标题与正则表达式不同。然后代码就失败了

感谢您的帮助, 谢谢

输出


你需要两个艺术家中的一个作为结果吗?是的,我需要第一个艺术家,因为通常第一个提到的艺术家是主艺术家,其余的是ColAbshanks,但是对于像-
ABC feat XYZ
这样的测试用例,这失败了。结果-
ABC专长
。虽然我期待ABCthanks,但这在很大程度上是可行的。你能解释一下这是怎么回事吗?因为您只是将
feat
替换为“”。但是它也适用于其他模式,如
&
@default-303。搜索两个用任何符号分隔的单词
,然后只会得到第一个出现的
组(0)
@default-303不客气,您也可以接受我的解决方案。当然,我刚刚做了:)
text = 'Anne-Marie & James Arthur'
text = "Calvin Harris, Rag'n'Bone Man"
text = 'DJ Snake feat. J Balvin'
text = 'ABC feat. XYZ'
re.search('\w+.\w+', text).group(0).replace(' feat', '')
Anne-Marie
Calvin Harris
DJ Snake
ABC