gpt4 book ai didi

python - 从 pandas 数据帧内的 nltk.stanford.StanfordDependencyParser 中解压 list_iterator

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:13 25 4
gpt4 key购买 nike

我正在尝试在 pandas DataFrame 内使用斯坦福依赖解析器。

from nltk.parse import stanford
import pandas as pd
dep_parser=stanford.StanfordDependencyParser()
df = pd.DataFrame({'ID' : [0,1,2], 'sentence' : ['This is the first s.', 'This is the 2nd s.', 'This isn''t the third s.']})
df['parsed'] = df.sentence.apply(dep_parser.raw_parse)
print(df)

ID sentence parsed
0 0 This is the first s. <list_iterator object at 0x000000000E849C18>
1 1 This is the 2nd s. <list_iterator object at 0x000000000E8691D0>
2 2 This isnt the third s. <list_iterator object at 0x000000000E8696A0>

但我更喜欢 DataFrame 列内部依赖图的文本表示,而不是迭代器,如下所示:

    ID                sentence                                        parsed
0 0 This is the first s. [[(('s.', 'NN'), 'nsubj', ('This', 'DT')),(('s.', 'NN'), 'cop', ('is', 'VBZ')), (('s.', 'NN'), 'det', ('the', 'DT')),(('s.', 'NN'), 'amod', ('first', 'JJ'))]]
...

我尝试按照 pandas 中的步骤遵循 nltk 文档,但会导致属性错误:

 df['dep'] = [list(parse.triples()) for parse in df.parsed]
AttributeError: 'list_iterator' object has no attribute 'triples'

有没有办法解压在 DataFrame 中显示为值的迭代器?欢迎任何帮助。

最佳答案

list_iterator 是一种“按需”生成列表的机制。它确实没有方法 triples(),但它在您的情况下生成的列表确实是一个三元组列表:

df['dep'] = [list(parse) for parse in df['parsed']]

关于python - 从 pandas 数据帧内的 nltk.stanford.StanfordDependencyParser 中解压 list_iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41274728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com