0
    import nltk
    from itertools import groupby


    def get_continuous_chunks(tagged_sent):
        continuous_chunk = []
        current_chunk = []

        for token, tag in tagged_sent:
            if tag != "O":
                current_chunk.append((token, tag))
            else:
                if current_chunk: # if the current chunk is not empty
                    continuous_chunk.append(current_chunk)
                    current_chunk = []
        # Flush the final current_chunk into the continuous_chunk, if any.
        if current_chunk:
            continuous_chunk.append(current_chunk)
        return continuous_chunk

    ne_tagged_sent = [('Rami', 'PERSON'), ('Eid', 'PERSON'), ('is', 'O'), ('studying', 'O'), ('at', 'O'), ('Stony', 'ORGANIZATION'), ('Brook', 'ORGANIZATION'), ('University', 'ORGANIZATION'), ('in', 'O'), ('NY', 'LOCATION')]

    named_entities = get_continuous_chunks(ne_tagged_sent)
    named_entities = get_continuous_chunks(ne_tagged_sent)
    named_entities_str = [" ".join([token for token, tag in ne]) for ne in named_entities]
    named_entities_str_tag = [(" ".join([token for token, tag in ne]), ne[0][1]) for ne in named_entities]

    def parser(n,string):
        for i in named_entities_str_tag[n]:
            if i==string:
                pass
            else:
                return i


print named_entities_str_tag
print

我从上面的代码中得到了这个输出:

('PERSON', 'Rami Eid')
('ORGANIZATION', 'Stony Brook University')
('LOCATION', 'NY')
('PERSON', 'GuruRaj Bagali')
('ORGANIZATION', 'Christ University')

但我希望它应该是像具有组织和位置的人这样的地图,我想以 json 格式存储它。

4

2 回答 2

0

您应该将数据格式化为字典,每个条目对应一个人,例如:

import json
data = {
        'Rami Eid':{'job': 'engineer', 'location':'NY'},
        'GuruRaj Bagali':{'job': 'professor', 'location': 'NY'}
       }
#Save it in a json file
json.dump(data, open('path/to_your_file', 'w')
于 2016-02-03T12:01:12.440 回答
0

目前还不清楚 ne_tagged_sent 列表包含什么(每个人、组织是否有一个 LOCATION ?),您必须澄清一下,我们才能回答您的问题。

于 2016-02-03T11:23:00.350 回答