我正在将文本写入 cdr (chordpro) 转换器,但在检测表格上的和弦线时遇到问题:
Cmaj7 F#m C7
Xxx xxxxxx xxx xxxxx xx x xxxxxxxxxxx xxx
这是我的 python 代码:
def getChordMatches(line):
import re
notes = "[CDEFGAB]";
accidentals = "(#|##|b|bb)?";
chords = "(maj|min|m|sus|aug|dim)?";
additions = "[0-9]?"
return re.findall(notes + accidentals + chords + additions, line)
我希望它返回一个列表 ["Cmaj7", "F#m", "C7"]。上面的代码不起作用,我一直在努力阅读文档,但我一无所获。
为什么将类和组链接在一起不起作用?
编辑
谢谢,我最终得到了以下内容,其中涵盖了我的大部分需求(例如,它不符合 E#m11)。
def getChordMatches(line):
import re
notes = "[ABCDEFG]";
accidentals = "(?:#|##|b|bb)?";
chords = "(?:maj|min|m|sus|aug|dim)?"
additions = "[0-9]?"
chordFormPattern = notes + accidentals + chords + additions
fullPattern = chordFormPattern + "(?:/%s)?\s" % (notes + accidentals)
matches = [x.replace(' ', '').replace('\n', '') for x in re.findall(fullPattern, line)]
positions = [x.start() for x in re.finditer(fullPattern, line)]
return matches, positions
最佳答案
您应该通过将 (...)
更改为 (?:...)
来使您的组不捕获。
accidentals = "(?:#|##|b|bb)?";
chords = "(?:maj|min|m|sus|aug|dim)?";
在线查看它:ideone
当您有捕获组时它不起作用的原因是它只返回那些组而不是整个匹配项。来自文档:
re.findall(pattern, string, flags=0)
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.
关于python - 我需要帮助编写用于检测和弦的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14031118/