【发布时间】:2018-06-02 16:42:30
【问题描述】:
我想通过在动词前添加“X”来标记句子中动词的位置。我的函数采取以下步骤来实现这一点。
- 找到动词。我使用 spaCy 进行 POS 标记。 SpaCy 输出我称之为
pos的 POS 标签列表,其中句子中的每个单词都表示为一个标签。 - 将句子也转换为列表
L。 - 确定词性列表中动词标签(例如
"VBZ")的索引x。 - 将索引
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."
我的问题有两个:
是否可以在 spaCy 中排除某些 POS 标签?例如,我可以排除 ['-LRB-', '-RRB-', etc.] 吗?这将使长度 pos == 长度 L
如果这不可能,我应该如何更改我的功能,以便可以指定从
['-LRB-', '-RRB-', etc.]删除的 POS 标签列表pos以便 pos-list 的长度与句子列表的长度?
【问题讨论】:
标签: python-3.x pandas spacy