例如,中文有元音和辅音
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。
我想使用正则表达式提取像
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