我想通过在动词前加一个“X”来标记动词在句子中的位置。我的函数执行以下步骤来实现这一点。
pos
,其中句子中的每个单词都表示为一个标签。L
。"VBZ"
)的索引x
。x
处。步骤4假设列表pos
的长度与句子列表L
的长度相同。通常情况就是这样,除非spaCy将标签分配给不单独索引的语句元素。在这种情况下,词性列表比句子列表更长。例如,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
比句子列表L
长,所以结果是:
x = "Dr. John (a fictional chartacter) never shakes hands. X"
但我想要的是:
x = "Dr. John (a fictional chartacter) never X shakes hands."
我的问题有两个:
pos
中删除的词性标签列表,以便pos-list的长度与句子列表的长度相同?发布于 2018-06-03 01:20:59
标记化比拆分更复杂。即使删除标记,也不会使split与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."))
https://stackoverflow.com/questions/50659061
复制相似问题