从它们来自的句子中标记单词

时间:2019-03-20 07:46:57

标签: python pandas indexing nlp nltk

我有一个包含3列的数据框,即'word','pos-tag','label'。这些单词最初来自文本文件。现在,我想在另一列“ sentences#”中说明单词最初来自的句子的索引。

Current state:-
WORD POS-Tag Label
my   PRP$     IR
name  NN      IR 
is   VBZ      IR
ron  VBN      PERSON
.     .
my   PRP$     IR
name NN       IR
is   VBZ      IR
harry VBN     Person
.      .      IR
Desired state:-
Sentence#  WORD    Pos-Tag  Label
 1          My       PRP      IR
 1          name     NN       IR
 1           is      VBZ      IR
 1           ron     VBN      Person
 1            .       .       IR
 2            My     PRP      IR
 2            name   NN       IR
 2             is    VBZ      IR
 2           harry   VBN      Person
 2              .     .       IR
我到目前为止使用的

代码:-

#necessary libraries
import pandas as pd
import numpy as np
import nltk 
import string
document=open(r'C:\Users\xyz\newfile.txt',encoding='utf8')
content=document.read()

sentences = nltk.sent_tokenize(content)
sentences = [nltk.word_tokenize(sent) for sent in sentences]
sentences = [nltk.pos_tag(sent) for sent in sentences]


flat_list=[]

# flattening a nested list
for x in sentences:
    for y in x:
        flat_list.append(y)

df = pd.DataFrame(flat_list, columns=['word','pos_tag']) 

#importing data to create the 'Label' column
data=pd.read_excel(r'C:\Users\xyz\pname.xlsx')
pname=list(set(data['Product']))

df['Label']=['drug' if x in fl else 'IR' for x in df['word']]

1 个答案:

答案 0 :(得分:0)

只需使用带有适当标点符号的split()预先将内容分成几行即可。将每一行存储在某个列表中,然后将索引存储在enumerate(lines)中:做您通常要做的事情,并将索引添加到df中。