正規表現を使用して、入力テキスト ファイルから和音を抽出します。ほとんどの場合は機能しますが、特定のファイルで失敗します。
これは私の正規表現コードです:
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 = [removeWhitespaces(x) for x in re.findall(fullPattern, line)]
positions = [x.start() for x in re.finditer(fullPattern, line)]
return matches, positions
これが機能したときの結果です。
line: Em C C/B
matches: [u'Em', u'C', u'C/B']
position: [5, 20, 23]
この行は、正しい結果を生成しないファイルからのものです。
line: Am Am/G D7/F# Fmaj7
matches: [u'Fmaj7']
position: [48]
どこから掘り始めればいいですか?エンコーディング、特殊文字、タブ、... ?
編集
これは、上記の出力の場所です。
line = unicode(l, encoding='utf-8')
matches, positions = getChordMatches(line)
print ' line:', line
print ' matches:', matches
print 'position:', positions
編集
完全な正規表現パターンは次のとおりです。
[ABCDEFG](?:#|##|b|bb)?(?:maj|min|m|sus|aug|dim)?[0-9]?(?:/[ABCDEFG](?:#|##|b|bb)?)?\s
編集
失敗した行の 16 進ダンプ (と思います):
hexdump -s 45 -n 99 input.txt
000002d 20 41 6d 20 20 20 20 20 20 20 20 20 20 41 6d 2f
000003d 47 20 c2 a0 20 20 20 20 20 20 44 37 2f 46 23 20
000004d 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
000005d 46 6d 61 6a 37 0a 49 20 6c 6f 6f 6b 20 61 74 20
000006d 79 6f 75 20 61 6c 6c 20 73 65 65 20 74 68 65 20
000007d 6c 6f 76 65 20 74 68 65 72 65 20 74 68 61 74 27
000008d 73 20 73
0000090
編集
受け入れられた回答で述べたように、改行されていないスペースが原因でした。を使用line = unicode(l, encoding='utf-8').replace(u"\u00A0", " ")
すると問題が解決します。