Python正则表达式检测音乐和弦? (修改的)

标签 python regex

我正在用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/

相关文章:

python - 在 TKinter 中禁用/启用按钮

python - 我如何知道亚马逊是否成功发送电子邮件

python - 按时间间隔+聚合函数对 Pandas 进行分组

javascript - 为什么 'B' 与 [a-z] 匹配?

regex - Angular 输入限制指令 - 否定正则表达式

python - Django 中的非主外键

python - 为什么我的嵌套 while 循环不起作用

java - 不考虑空格的正则表达式

java - 来自缓存字符串的 Pattern.compile() 与缓存已编译模式

javascript - 用于匹配重复子字符串的单个 js 正则表达式?