python - 如何在 NLTK 词性 (POS) 标记中仅获取所选标记的单词?

标签 python list pandas tuples nltk

抱歉,我是 Pandas 和 NLTK 的新手。我正在尝试构建一组自定义返回的 POS。我的数据内容:

        comment
0       [(have, VERB), (you, PRON), (pahae, VERB)]
1       [(radio, NOUN), (television, NOUN), (lid, NOUN)]
2       [(yes, ADV), (you're, ADJ)]
3       [(ooi, ADJ), (work, NOUN), (barisan, ADJ)]
4       [(national, ADJ), (debt, NOUN), (increased, VERB)]

知道如何才能只获取与所选标签匹配的单词(VERBNOUN),如下所示?如果没有匹配,则返回 NaN

        comment
0       [(have), (pahae)]
1       [(radio), (television), (lid)]
2       [NaN]
3       [(work)]
4       [(debt), (increased)]

最佳答案

您可以使用列表理解,然后将空的list替换为[NaN]:

df = pd.DataFrame({'comment': [
        [('have', 'VERB'), ('you', 'PRON'), ('pahae', 'VERB')],
        [('radio', 'NOUN'), ('television', 'NOUN'), ('lid', 'NOUN')],
        [('yes', 'ADV'), ("you're", 'ADJ')],
        [('ooi', 'ADJ'), ('work', 'NOUN'), ('barisan', 'ADJ')],
        [('national', 'ADJ'), ('debt', 'NOUN'), ('increased', 'VERB')]
    ]})

print (df)    
                                             comment
0         [(have, VERB), (you, PRON), (pahae, VERB)]
1   [(radio, NOUN), (television, NOUN), (lid, NOUN)]
2                        [(yes, ADV), (you're, ADJ)]
3         [(ooi, ADJ), (work, NOUN), (barisan, ADJ)]
4  [(national, ADJ), (debt, NOUN), (increased, VE...
df.comment = df.comment.apply(lambda x: [(t[0],) for t in x if t[1]=='VERB' or t[1]=='NOUN'])
df.ix[df.comment.apply(len) == 0, 'comment'] = [[np.nan]]
print (df)
                             comment
0                [(have,), (pahae,)]
1  [(radio,), (television,), (lid,)]
2                              [nan]
3                          [(work,)]
4            [(debt,), (increased,)]

关于python - 如何在 NLTK 词性 (POS) 标记中仅获取所选标记的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39483108/

相关文章:

python - 如何从 ASCII 文件写入/读取带有 MultiIndex 的 Pandas DataFrame?

python - 如何拆分句子,只让 ascii 字符

Python - 遍历具有特定格式输出的列表列表;文件输出

java - 从一种方法到另一种方法的访问列表

python - 计算包含 None 类型的列表的均值和最小值

python - 在多索引 DF 中按索引值选择

python - matplotlib:使图例出现在其他子图上方

不可变集合的 Python 类型 : `Final[Set[T]]` vs `FrozenSet[T]`

python - 为什么 Streamlit 找不到我的 python 文件?

python - 从整个数据框中删除重复值