我正在用Python开发一个和弦转置器,并且大多数东西都可以工作,但是我的正则表达式有一些问题,我想知道是否有人在正则表达式方面比我更聪明怎么修。我本质上使用的是在另一个线程中找到的这个正则表达式:
import re
def findChords(line):
notes = "[CDEFGAB]";
accidentals = "(?:#|##|b|bb)?";
chords = "(?:maj|min|m|sus|aug|dim)?";
additions = "[0-9]?"
return re.findall(notes + accidentals + chords + additions, line)
# Case 1, which works:
line = "A A7 Am7 Bb Cmaj7"
print findChords(line)
['A', 'A7', 'Am7', 'Bb', 'Cmaj7']
# Case 2, which thinks the capital C in chorus is a chord.
line = "Chorus: A A7 Am7 Bb Cmaj7"
print findChords(line)
['C', 'A', 'A7', 'Am7', 'Bb', 'Cmaj7']
如您所见,上面的“情况 1”效果很好。然而,“案例2”失败了,认为“Chorus”一词中的大写C是和弦。
有什么办法可以修改正则表达式的“注释”部分,使其足够智能以进行这种省略吗?它还应该省略“Baseball”中的“B”等内容。
感谢您的帮助。
最佳答案
将 r'\b'
添加到正则表达式的开头,将 r'(?!\w)'
添加到正则表达式的末尾,以便正则表达式可以仅与完整单词匹配(其中“单词”是字母数字字符和/或下划线的序列):
def findChords(line):
notes = "[CDEFGAB]";
accidentals = "(?:#|##|b|bb)?";
chords = "(?:maj|min|m|sus|aug|dim)?";
additions = "[0-9]?"
return re.findall(r'\b' + notes + accidentals + chords + additions + r'(?!\w)', line)
(请注意,我们不能在末尾使用 r'\b'
,因为这样以 #
结尾的和弦将永远不会被接受。)
关于Python正则表达式检测音乐和弦? (修改的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24946412/