我正在用Python开发一个和弦转置器,大多数东西都能正常工作,但是我的regex有几个问题,我想知道是否有比我更聪明的人知道如何解决这个问题。我基本上使用的是另一个线程中的正则表达式:
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是一个和弦。你知道吗
有什么办法可以修改regex的“notes”部分,使其聪明到可以进行这种省略吗?它还应该省略“棒球”中的“B”等词
谢谢你的帮助。你知道吗
将
r'\b'
添加到正则表达式的开头,将r'(?!\w)'
添加到结尾,使正则表达式只能与完整单词匹配(其中“单词”是一系列字母数字字符和/或下划线):(请注意,我们不能在结尾处使用
r'\b'
,因为这样就永远不会接受以#
结尾的和弦。)相关问题 更多 >
编程相关推荐