例如,中文有元音和辅音

vowels  = ['a', 'ai', 'an', 'ang', 'ao', 'e', 'ei', 'en', 'eng', 'er', 'i', 'ia', 'ian', 'iang', 'iao', 'ie', 'ii', 'iii', 'in', 'ing', 'iong', 'iou', 'o', 'ong', 'ou', 'u', 'ua', 'uai', 'uan', 'uang', 'uei', 'uen', 'ueng', 'uo', 'v', 'van', 've', 'vn', 'zh']

consonants = ['b','c','ch', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 'sh',' sp', 'sil', 't', 'x', 'z']


假设我有这样的三通电话:

三音素“ a-b + c”表示先前的,当前的,以下的音素是a,b和c。

python - 如何使用正则表达式匹配典型的三电话?-LMLPHP

我想使用正则表达式提取像vowel-vowel+**-vowel+vowel这样的相邻元音模式。

例如


  匹配:zh-uei + x,b-ai + vn,e-uang + x
  
  不匹配:sil-z + ai,vn-l + v,x-ia + f


我使用以下代码:

v = '|'.join(vowels)           # Or v = '^'+'|'.join(consonants)
p = r'({0}\-{0}\+.*)|(.*\-{0}\+{0})'.format(v)


但是,re.match(p,'z-en+iang')仍为False。那么如何解决呢?谢谢

最佳答案

import re

vowels  = ['a', 'ai', 'an', 'ang', 'ao', 'e', 'ei', 'en', 'eng', 'er', 'i', 'ia', 'ian', 'iang', 'iao', 'ie', 'ii', 'iii', 'in', 'ing', 'iong', 'iou', 'o', 'ong', 'ou', 'u', 'ua', 'uai', 'uan', 'uang', 'uei', 'uen', 'ueng', 'uo', 'v', 'van', 've', 'vn', 'zh']
consonants = ['b','c','ch', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 'sh','sp', 'sil', 't', 'x', 'z']
# joining vowels with |
vowels_string = '|'.join(vowels)
# joining consonants with |
consonants_string = '|'.join(consonants)

# joining all characters with |
all_chars = "{}|{}".format(vowels_string, consonants_string)

reg1 = '^(?:{1})-(?:{0})\+(?:{0})$'.format(vowels_string, all_chars) # allchars-vowel+vowel
reg2 = '^(?:{0})-(?:{0})\+(?:{1})$'.format(vowels_string, all_chars) # vowel-vowel+allchars

# compiling the regex
regex = re.compile(
    '({})|({})'.format(reg1, reg2)
)

# testing
print(re.match(regex, 'zh-uei+x'))
print(re.match(regex, 'b-ai+vn'))
print(re.match(regex, 'e-uang+x'))
print(re.match(regex, 'z-en+iang'))

print(re.match(regex, 'sil-z+ai'))
print(re.match(regex, 'vn-l+v'))
print(re.match(regex, 'x-ia+f'))



vowels_string包含所有用或(|)分隔的元音
consonants_string包含以或(|)分隔的所有辅音
all_chars包含用或(|)分隔的所有字符


正则表达式如下:(1是all_chars,0是vowels_string

'^ -> beginning of string
(?:{1})  -> all characters
-
(?:{0}) -> vowels
\+
(?:{0}) -> vowels
$'-> end of string

10-06 07:17