Python findall - 忽略一些结果
Python findall - ignoring some results
我正在做一个程序,将来会解释 YouTube 视频的搜索结果。我的代码片段版本旨在从歌曲标题中提取艺术家的假名。
例子
我在字符串中保存了一个标题:"Drake ft. DJ Khalid, Nicki Minaj - 'Why Futures' (Official video)" 我想忽略 'Futures' 这个词 findall函数(因为是主打歌的一部分,不是rapper's/artist的昵称),在'和"字符之间。
此外,我对 'DJ Khalid' 有疑问,因为 findall returns 说唱歌手的两个昵称(DJ Khalid 和 Khalid)而不是一个昵称(应该是同一个 DJ Khalid)。
代码
edit_string = "Drake ft. DJ Khalid, Nicki Minaj - "Why Futures" (Official video)"
rapper_name = open_csv() #list of rapper's nicks
new_title = []
for rapper_name in rappers_list:
yer = ''.join(rapper_name)
if re.findall(yer.lower(),edit_string.lower()): new_title.append(yer)
new_title = ' x '.join(new_title)
print(new_title)
edit_string = new_title
结果
实际结果是:Drake x Khalid x Nicki Minaj x DJ Khalid x Future
(因为不幸的是在我的说唱歌手名单中我有一个叫 Future 的人)
应为:Drake x DJ Khalid x Nicki Minaj
如何以最好的方式(最佳优化)做到这一点?预先感谢您的所有帮助。
模式归功于@FailSafe。 OP,这个答案证明了@FailSafe 的建议确实是正确的:
import re
edit_string = "Drake ft. DJ Khalid, Nicki Minaj - "Why Futures " (Official video)"
rappers_list = ['Drake', 'DJ Khalid', 'Nicki Minaj', 'Future']#open_csv() #list of rapper's nicks
new_title = []
for rapper_name in rappers_list:
yer = '(?i)\b'+str(rapper_name)+'\b'
if re.findall(yer.lower(), edit_string.lower()):
new_title.append(rapper_name)
new_title = ' x '.join(new_title)
print(new_title)
edit_string = new_title
Output:
## Drake x DJ Khalid x Nicki Minaj
我正在做一个程序,将来会解释 YouTube 视频的搜索结果。我的代码片段版本旨在从歌曲标题中提取艺术家的假名。
例子
我在字符串中保存了一个标题:"Drake ft. DJ Khalid, Nicki Minaj - 'Why Futures' (Official video)" 我想忽略 'Futures' 这个词 findall函数(因为是主打歌的一部分,不是rapper's/artist的昵称),在'和"字符之间。 此外,我对 'DJ Khalid' 有疑问,因为 findall returns 说唱歌手的两个昵称(DJ Khalid 和 Khalid)而不是一个昵称(应该是同一个 DJ Khalid)。
代码
edit_string = "Drake ft. DJ Khalid, Nicki Minaj - "Why Futures" (Official video)"
rapper_name = open_csv() #list of rapper's nicks
new_title = []
for rapper_name in rappers_list:
yer = ''.join(rapper_name)
if re.findall(yer.lower(),edit_string.lower()): new_title.append(yer)
new_title = ' x '.join(new_title)
print(new_title)
edit_string = new_title
结果
实际结果是:Drake x Khalid x Nicki Minaj x DJ Khalid x Future
(因为不幸的是在我的说唱歌手名单中我有一个叫 Future 的人)
应为:Drake x DJ Khalid x Nicki Minaj
如何以最好的方式(最佳优化)做到这一点?预先感谢您的所有帮助。
模式归功于@FailSafe。 OP,这个答案证明了@FailSafe 的建议确实是正确的:
import re
edit_string = "Drake ft. DJ Khalid, Nicki Minaj - "Why Futures " (Official video)"
rappers_list = ['Drake', 'DJ Khalid', 'Nicki Minaj', 'Future']#open_csv() #list of rapper's nicks
new_title = []
for rapper_name in rappers_list:
yer = '(?i)\b'+str(rapper_name)+'\b'
if re.findall(yer.lower(), edit_string.lower()):
new_title.append(rapper_name)
new_title = ' x '.join(new_title)
print(new_title)
edit_string = new_title
Output:
## Drake x DJ Khalid x Nicki Minaj