【问题标题】:Splitting a string after punctuation while including punctuation在标点符号后拆分字符串,同时包含标点符号
【发布时间】:2012-01-22 12:09:12
【问题描述】:

我正在尝试通过正则表达式将一串单词拆分为单词列表。我还是个正则表达式的初学者。

我正在使用 nltk.regex_tokenize,它产生的结果很接近,但不是我想要的。

这是我目前所拥有的:

>>> import re, codecs, nltk
>>> sentence = "détesté Rochard ! m'étais à... 'C'est hyper-cool.' :) :P"    
>>> pattern = r"""(?x)
    #words with internal hyphens
    | \w+(-\w+)*
    #ellipsis
    | \.\.\.
    #other punctuation tokens
    | [][.,;!?"'():-_`]
    """ 
>>> nltk.regexp_tokenize(sentence.decode("utf8"), pattern)
[u'd\xe9test\xe9', u'Rochard', u'!', u'm', u"'", u'\xe9tais', u'\xe0', u'qu', u"'", u'on', u'...', u"'", u'C', u"'", u'est', u'hyper-cool', u'.', u"'", u':', u')', u':', u'P']

我希望输出如下:

[u'd\xe9test\xe9', u'Rochard', u'!', u"m'", u'\xe9tais', u'\xe0', u"qu'", u'on', u'...', u"'", u"C'", u'est', u'hyper-cool', u'.', u"'", u':)', u':P']

我有一个“表情符号”的解决方法,所以我最关心的是引号。

【问题讨论】:

    标签: python regex nltk punctuation tokenize


    【解决方案1】:

    看起来想要的输出和你输入的句子不一致

    1. [u"qu'", u'on'] :我不知道这两个匹配是从哪里确定的,从你的句子中确定
    2. 为什么u'.' 不是u'hyper-cool' 的一部分(假设您希望将标点符号作为单词的一部分。
    3. 为什么u"'" 不是u"C'" 的一部分。 (假设您希望将标点符号作为单词的一部分。

    此外,如果您只想拆分正则表达式,除了拆分行之外,还有什么理由使用 nltk 吗?我没有使用nltk 的经验,所以只提出regex 解决方案。

    >>> sentence
    u"d\xe9test\xe9 Rochard ! m'\xe9tais \xe0... 'C'est hyper-cool.' :) :P"
    >>> pattern=re.compile(
        u"(" #Capturing Group
        "(?:" #Non Capturing
        "[\.\.\.\]\[\.,;\!\?\"\'\(\):-_`]?" #0-1 punctuation
        "[\w\-]+"                           #Alphanumeric Unicode Word with hypen
        "[\.\.\.\]\[\.,;\!\?\"\'\(\):-_`]?" #0-1 punctuation
        ")"
        "|(?:[\.\.\.\]\[\.,;\!\?\"\'\(\):-_`]+)" #1- punctuation
         ")",re.UNICODE)
    >>> pattern.findall(sentence)
    [u'd\xe9test\xe9', u'Rochard', u'!', u"m'", u'\xe9tais', u'\xe0.', u'..', u"'C'", u'est', u'hyper-cool.', u"'", u':)', u':P']
    

    看看这是否适合你

    如果您需要有关捕获组、非捕获组、字符类、Unicode 匹配和 findall 的更多信息,我建议您粗略浏览一下 python 的 re 包。 此外,我不确定您在多行中继续字符串的方式在这种情况下是否合适。如果您需要有关跨行拆分字符串(不是多行字符串)的更多信息,请查看this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      • 2017-01-12
      相关资源
      最近更新 更多