【问题标题】:Python 2.7 Regex Tokenizer Implementation Not Working [duplicate]Python 2.7 Regex Tokenizer 实现不起作用[重复]
【发布时间】:2017-06-24 13:19:15
【问题描述】:

我创建了一个正则表达式来匹配德语 text 中的标记,它的类型为 string

我的正则表达式使用regex101.com 按预期工作。这是我的正则表达式的链接,带有一个例句: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.UNICODE 选项编译您的正则表达式,以允许 \w 匹配非 ASCII 字母 - 毕竟,有些德语单词包含除变音符号,而您现在正在错过这些。

标签: regex python-2.7 tokenize


【解决方案1】:

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

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

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€']

【讨论】:

    猜你喜欢
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 2020-07-10
    • 2014-06-01
    相关资源
    最近更新 更多