代码之家  ›  专栏  ›  技术社区  ›  Programmer_nltk

如何在字符串周围添加标点符号?[复制品]

  •  0
  • Programmer_nltk  · 技术社区  · 7 年前

    这个问题已经有了答案:

    我想在标识为nns的单词周围添加方括号。能够将其识别为单个单词,如何将其与句子重新连接。

    import spacy, re
    
    nlp = spacy.load('en_core_web_sm')
    s = u"The cats woke up but the dogs slept."
    
    doc = nlp(s)
    for token in doc:
        if (token.tag_ == 'NNS'):
            print ([token])
    

    当前结果:

    [cats]
    [dogs]
    

    预期结果:

    The [cats] woke up but the [dogs] slept.
    
    3 回复  |  直到 7 年前
        1
  •  3
  •   Mike Burr    7 年前

    sentence = []
    doc = nlp(s)
    for token in doc:
        if (token.tag_ == 'NNS'):
            sentence.append('[' + token + ']')
        else:
            sentence.append(token)
    
    sentence = ' '.join(sentence)
    
        2
  •  2
  •   Dani Mesejo    7 年前

    import spacy
    
    nlp = spacy.load('en_core_web_sm')
    s = u"The cats woke up but the dogs slept."
    
    doc = nlp(s)
    print(' '.join(['[{}]'.format(token) if token.tag_ == 'NNS' else '{}'.format(token) for token in doc])
    
        3
  •  0
  •   Programmer_nltk    7 年前
    import spacy
    
    nlp = spacy.load('en_core_web_sm')
    s = u"The cats woke up but the dogs slept."
    doc = nlp(s)
    sentence = []
    doc = nlp(s)
    for token in doc:
        if (token.tag_ == 'NNS'):
            sentence.append('[' + (token.text) + ']')
        else:
            sentence.append(token.text)
    
    sentence = ' '.join(sentence)
    print sentence
    

    The [cats] woke up but the [dogs] slept .