Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式检测音乐和弦?(修改)_Python_Regex - Fatal编程技术网

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

Python正则表达式检测音乐和弦?(修改),python,regex,Python,Regex,我正在用Python开发一个和弦转置器,大多数东西都能正常工作,但是我的正则表达式有几个问题,我想知道,在正则表达式方面,是否有比我更聪明的人知道如何解决这个问题。我基本上使用的是另一个线程中的正则表达式: import re def findChords(line): notes = "[CDEFGAB]"; accidentals = "(?:#|##|b|bb)?"; chords = "(?:maj|min|m|sus|aug|dim)?"; addit

我正在用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”失败了,认为“合唱”一词中的大写字母C是和弦

有什么办法可以修改正则表达式的“notes”部分,使其足够聪明,可以进行这种省略吗?它还应该省略“棒球”中的“B”等词


感谢您的帮助。

r'\b'
添加到正则表达式的开头,并将
r'(?!\w)
添加到结尾,这样正则表达式就只能与完整的单词匹配(其中“单词”是一系列字母数字字符和/或下划线):


(请注意,我们不能在结尾处使用
r'\b'
,因为这样就永远不会接受以
#
结尾的和弦。)

谢谢!很好用。太棒了,我也要试试这个。。。
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)