与熊猫高效分块

时间:2017-11-22 17:31:40

标签: python-3.x pandas nltk

我正在使用一个可以包含大量内容的pandas框架,并且对于每个文档,我需要获得一些定义的名词短语。虽然一切正常但它也有点慢,我确信有更好的方法可以达到相同的效果,但我的python知识还不够好。

因此,任何关于如何改进的建议都将受到高度赞赏。

这是我的代码:

import pandas
import nltk, re
from nltk.tokenize import sent_tokenize, word_tokenize, regexp_tokenize, wordpunct_tokenize
from nltk.chunk import *
from nltk.chunk.util import *
from nltk.chunk.regexp import *
from nltk import untag

def chunckMe(str,rule):

    np=[]
    chunk_parser = RegexpChunkParser(rule, chunk_label='LBL')
    sentences= sent_tokenize(str)

    for sent in sentences:
        d_words=nltk.word_tokenize(sent)
        d_tagged=nltk.pos_tag(d_words)
        chunked_text = chunk_parser.parse(d_tagged)

        tree = chunked_text
        for subtree in tree.subtrees():
            if subtree.label() == 'LBL': np.append(" ".join(untag(subtree)).lower())

    return np;

# main def
def rm_main(data):

    np_all=[]

    # This works but can probably be done much better ...

    for index,row in data.iterrows():

        str=row["txt"]

        chunk_rule = ChunkRule("<JJ.*><NN.*>+|<JJ.*>*<NN.*><CC>*<NN.*>+|<CD><NN.*>", "Simple noun phrase")
        tags = chunckMe(str,[chunk_rule])
        np_all.append(', '.join(set(tags)))

    data['noun_phrases']=np_all

    return data

知道如何避免或改善iterrows部分吗?它有效,但我有强烈的感觉,有更好的方法来做到这一点。

0 个答案:

没有答案
相关问题