此python代码(列表操作)有什么问题?

时间:2019-02-21 10:31:19

标签: python numpy

我有一个数据集,并且我基于句子级别提取它们,这意味着每个句子都是列表的元素。

REL_LIST = np.array(['CEO', 'born', 'Professor', 'Employee', 'president']) # Relationship
len(SENT_LIST) # is 4 (`SENT_LIST` is list of sentences from a file)

len(REL_LIST) # is 5 (`REL_LISt` is the words or relations in each sentence)

vector1 # is a numpy array, contains those elements extracted by NAMED ENTITY Recognition of Polyglot. such as (I-PER(['M.', 'Ashraf']) I-LOC(['Afghanistan'])

LEN_SENT = 0
word = 0
while word <= len(REL_LIST):
    if REL_LIST[word] in SENT_LIST[LEN_SENT][:]:
        k = np.insert(vector1[LEN_SENT], word, REL_LIST[word])
        print(k) # `vector1` is a numpy array include NER from polyglot.
    LEN_SENT = LEN_SENT + 1
    word = word + 1
    if LEN_SENT == len(SENT_LIST) and word == LEN_SENT:
        break # because length of `sentence` and `REL_LIST` is not the same

它仅输出第一个元素的关系,而不是全部。为什么?

 ['President' I-PER(['M.', 'Ashraf']) I-LOC(['Afghanistan'])]

1 个答案:

答案 0 :(得分:0)

您同时增加LEN_SENTword。 那是问题。

要检查每个句子的每个单词,您需要两个嵌套循环。

尝试类似的东西:

LEN_SENT = 0
word = 0
for LEN_SENT in range(len(SENT_LIST)):
    for word in range(len(REL_LIST)):
        if REL_LIST[word] in SENT_LIST[LEN_SENT][:]:
            k = np.insert(vector1[LEN_SENT], word, REL_LIST[word])
            print(k) # `vector1` is a numpy array include NER from polyglot.