BanglaAlphabet = {
'Consonant' : '[\u0995-\u09B9\u09CE\u09DC-\u09DF]',
'IndependantVowel' : '[\u0985-\u0994]',
'DependantVowel' : '[\u09BE-\u09CC\u09D7]',
'Nukta' : '[\u09BC]'
}
BanglaWordPattern = ur"""(
({DependantVowel}{Nukta}{Consonant}) |
({DependantVowel}{Consonant}) |
{IndependantVowel} |
{Consonant} |
)+""".format(**BanglaAlphabet)
BanglaWordPattern = re.compile(BanglaWordPattern, re.VERBOSE)
匹配是通过以下方式完成的:
re.match(BanglaWordPattern, w[::-1])
这是为了从右到左匹配有效的孟加拉词而设计的。
然而,它在匹配时也会匹配无效的单词,比如 োগাড় 和 িদগ。
可能出了什么问题?
编辑
在 @GarethRees 和 @ChrisMorgan 的多次更正建议下,我最终得到:
bangla_alphabet = dict(
consonant = u'[\u0995-\u09b9\u09ce\u09dc-\u09df]',
independent_vowel = u'[\u0985-\u0994]',
dependent_vowel = u'[\u09be-\u09cc\u09d7]',
dependent_sign = u'[\u0981-\u0983\u09cd]',
virama = u'[\u09cd]'
)
bangla_word_pattern = re.compile(ur'''(?:
{consonant}
({virama}{consonant})?
({virama}{consonant})?
{dependent_vowel}?
{dependent_sign}?
|
{independent_vowel}
{dependent_sign}?
)+
匹配现在是这样的:
bangla_word_pattern.match(w)
这段代码不仅可以纠正错误,而且比以前涵盖了更多的字符和有效结构。
我很高兴地报告说它正在按预期工作。因此,这段代码现在作为验证孟加拉语单词语法的非常基本的正则表达式。
有几个特殊规则/异常没有实现。我将逐步研究并将它们添加到这个基本结构中。
许多''.format(**bangla_alphabet), re.VERBOSE)
匹配现在是:
xCodexBlockxPlacexHolderx
这段代码不仅可以纠正错误,而且比以前涵盖了更多的字符和有效结构。
我很高兴地报告说它正在按预期工作。因此,这段代码现在作为验证孟加拉语单词语法的非常基本的正则表达式。
有几个特殊规则/异常没有实现。我将逐步研究并将它们添加到这个基本结构中。
({virama}{consonant})?
中的(
改为(?:
以提高性能。 - Chris Morgan