【问题标题】:Is it possible to exclude certain POS tags in spaCy? Python是否可以在 spaCy 中排除某些 POS 标签? Python
【发布时间】:2018-06-02 16:42:30
【问题描述】:

我想通过在动词前添加“X”来标记句子中动词的位置。我的函数采取以下步骤来实现这一点。

  1. 找到动词。我使用 spaCy 进行 POS 标记。 SpaCy 输出我称之为 pos 的 POS 标签列表,其中句子中的每个单词都表示为一个标签。
  2. 将句子也转换为列表L
  3. 确定词性列表中动词标签(例如"VBZ")的索引x
  4. 将索引x 处的所需“X”标记插入句子列表。

步骤 4 假设列表 pos 的长度与句子列表 L 的长度相同。这通常是这种情况,除非 spaCy 将标签分配给 Python 未单独索引的句子元素。在这种情况下,POS 列表比句子列表长。例如,spaCy 将括号 '(' 或单词 '.' 后面的句号视为一个单独的位置,而 Python 则没有。因此,'X' 在句子中放错了位置。

如何解决?

下面是一个例子。

import pandas as pd
import spacy
nlp = spacy.load('en')

s = "Dr. John (a fictional chartacter) never shakes hands."
df = pd.DataFrame({'sentence':[s]})
k = df['sentence']

def marking(row):
    L = row
    sentence_spacy = nlp(L)
    pos = [] # store the pos tags in a list 'pos'
    for token in sentence_spacy:
        pos.append(token.tag_)
        print(pos)
    if "VBZ" in pos:
        x = pos.index("VBZ")
        L = L.split()
        L.insert(x, "X")
        L = " ".join(L) # split the sentence also in a list
        print(L)
        return L
x = k.apply(marking)
print(x)    

这给出了:

pos = ['NNP', 'NNP', '-LRB-', 'DT', 'JJ', 'NN', '-RRB-', 'RB', 'VBZ', 'NNS', '.']
L = ['Dr.', 'John', '(a', 'fictional', 'chartacter)', 'never', 'shakes', 'hands.']

并且因为pos-list pos比句子列表L长,所以结果是:

 x = "Dr. John (a fictional chartacter) never shakes hands. X"

但我想要这个:

x = "Dr. John (a fictional chartacter) never X shakes hands."

我的问题有两个:

  1. 是否可以在 spaCy 中排除某些 POS 标签?例如,我可以排除 ['-LRB-', '-RRB-', etc.] 吗?这将使长度 pos == 长度 L

  2. 如果这不可能,我应该如何更改我的功能,以便可以指定从 ['-LRB-', '-RRB-', etc.] 删除的 POS 标签列表 pos 以便 pos-list 的长度与句子列表的长度?

【问题讨论】:

    标签: python-3.x pandas spacy


    【解决方案1】:

    标记化比拆分更复杂。即使丢弃令牌也不会使拆分对应于 spaCy 的令牌(尝试nlp('non-trivial'))。幸运的是,有一个更好的方法:您可以从标记重构句子并在所需的点插入标记:

    def marking(row):
        chunks = []
        for token in nlp(row):
            if token.tag_ == 'VBZ':
                chunks.append('X')
            chunks.append(token.text_with_ws)
        return ' '.join(chunks)
    
    print(marking("Dr. John (a fictional chartacter) never shakes hands."))
    

    【讨论】:

    • 非常感谢。你能帮我理解这条线到底是做什么的吗? chunks.append(token.text_with_ws)
    • Tokens 有一个 text 属性,其中包含它们的非空白内容。如果你想重构输入句子,你需要标记之间的空格,你可以方便地从text_with_ws获得。
    • 太棒了!请在“摇晃”之前在您的答案中添加“X”?
    • “X”只是输出的一部分。
    • 哦,是的,你是对的。非常感谢这个答案。
    猜你喜欢
    • 1970-01-01
    • 2021-03-20
    • 2014-01-27
    • 2013-02-19
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    相关资源
    最近更新 更多