Python 2.7 正则表达式分词器实现不工作

Python 2.7 Regex Tokenizer Implementation Not Working

我创建了一个正则表达式来匹配 text 类型 string 中的标记。

我的正则表达式使用 regex101.com. Here is a link of my regex with an example sentence: My regex + example on regex101.com

按预期工作

所以我在 python 2.7 中这样实现了它:

GERMAN_TOKENIZER = r'''(?x) # set flag to allow verbose regex
([A-ZÄÖÜ]\.)+  # abbrevations including ÄÖÜ
|\d+([.,]\d+)?([€$%])? # numbers, allowing commas as seperators and € as currency
|[\wäöü]+ # matches normal words
|\.\.\. # ellipsis
|[][.,;\"'?():-_'!] # matches special characters including !
'''

def tokenize_german_text(text):
    '''
        Takes a text of type string and 
        tokenizes the text
    '''
    matchObject = re.findall(GERMAN_TOKENIZER, text)
    pass

tokenize_german_text(u'Das ist ein Deutscher Text! Er enthält auch Währungen, 10€')

结果:

当我调试它时,我发现 matchObject 只是一个包含 11 个空字符条目的列表。为什么它没有按预期工作,我该如何解决?

re.findall() 仅收集捕获组中的匹配项(除非您的正则表达式中没有捕获组,在这种情况下它会捕获每个匹配项)。

因此您的正则表达式匹配了几次,但每次匹配都是没有捕获组参与的匹配。删除捕获组,您将看到结果。另外,将 - 放在字符 class 的末尾,除非你真的想匹配 :_ 之间的字符范围(而不是 - 本身):

GERMAN_TOKENIZER = r'''(?x) # set flag to allow verbose regex
(?:[A-ZÄÖÜ]\.)+  # abbrevations including ÄÖÜ
|\d+(?:[.,]\d+)?[€$%]? # numbers, allowing commas as seperators and € as currency
|[\wäöü]+ # matches normal words
|\.\.\. # ellipsis
|[][.,;\"'?():_'!-] # matches special characters including !
'''

结果:

['Das', 'ist', 'ein', 'Deutscher', 'Text', '!', 'Er', 'enthält', 'auch', 'Währungen', ',', '10€']