从列表中的元组中提取带有NN标记的单词

问题描述 投票:-2回答:3

我试图在每个具有'NN'标签的元组中提取第0个元素。只想根据标签提取单词。例如。每行:

train['Tag'] = [('unclear', 'JJ'), ('incomplete', 'JJ'), ('instruction', 'NN'), ('given', 'VBN')]

我尝试使用where子句在每个元组中提取第一个元素

train['Tagged2']= [x[0] for x in train['Tag'] if x[1] in ("NN")]

预期结果,新列包含带有NN标记的单词的每一行,在示例中它将是单词'instruction'

python pandas list pos-tagger
3个回答
1
投票

==

如果两个操作数的值相等,则条件成立。

in

如果在指定序列中找到变量,则求值为true,否则求值为false。

因此:

使用比较运算符==而不是in

tt = [('unclear', 'JJ'), ('incomplete', 'JJ'), ('instruction', 'NN'), ('given', 'VBN')]

print([t[0] for t in tt if t[1] == 'NN'])

OUTPUT:

['instruction']

编辑:

自从您更新了问题:

train = {}    # Assuming that you're working with associative arrays i.e. dict in Py

train['Tag'] = [('unclear', 'JJ'), ('incomplete', 'JJ'), ('instruction', 'NN'), ('given', 'VBN')]

print([t[0] for t in train['Tag'] if t[1] == 'NN'])

OUTPUT:

['instruction']

pyFiddle


1
投票

由于你必须根据condtion创建新的pandas列,你可以使用下面的代码来过滤掉带有标签NN的单词

df = pd.DataFrame()
df['Tag'] = [('unclear', 'JJ'), ('incomplete', 'JJ'), ('instruction', 'NN'), ('given', 'VBN')]

# create 2 separate columns with tags and words
df['words'] = [i[0] for i in df['Tag']]
df['tags'] = [i[1] for i in df['Tag']]

# use np.where to find tags with `NN`
df['Tagged2'] = np.where(df['tags']=='NN', df['words'], np.nan)

df.drop(['words','tags'],1,inplace=True)
print(df)

输出:

                Tag      Tagged2                                                                                                     
0      (unclear, JJ)          NaN                                                                                                     
1   (incomplete, JJ)          NaN                                                                                                     
2  (instruction, NN)  instruction                                                                                                     
3       (given, VBN)          NaN 

0
投票
train['Tagged3']= train['subclause'].apply(lambda x:' '.join([word for (word, pos) in nltk.pos_tag(nltk.word_tokenize(x)) if pos[0] == 'N']))
© www.soinside.com 2019 - 2024. All rights reserved.