从词和词类生成多级词典

2024-05-16 15:18:10 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一些Penn Treebank以这种格式标记的文本:

“David/NNP Short/NNP will/MD主持/VB/DT会议/NN./。/DT boy/NN坐/VBZ在/DT椅子上/NN./。”

我想产生一个多层次的字典,有一个关键字和计数的频率,它似乎标记为每个位置,所以我们有['椅子,VB:1,NN:1','的,DT:3',]等

我想我可以使用正则表达式来提取单词和相应的位置

r'[A+Za+z]+/' and r'/[A+Z]+'

但是我不知道如何把这些放在一起,为一个单词和它对应的词性出现创造一个条目。你知道吗

有什么想法?你知道吗


Tags: 标记文本格式dtnn单词mdwill
1条回答
网友
1楼 · 发布于 2024-05-16 15:18:10

在这种情况下,不必使用正则表达式。你知道吗

您可以按空格拆分,然后用斜杠将结果收集到^{}defaultdictint

In [1]: import re

In [2]: from collections import defaultdict

In [3]: s = "David/NNP Short/NNP will/MD chair/VB the/DT meeting/NN ./. The/DT boy/NN sits/VBZ on/IN the/DT chair/NN
   ...:  ./."

In [4]: d = defaultdict(lambda: defaultdict(int))

In [5]: for item in s.split():
   ...:     word, tag = item.split("/")
   ...:     word = word.lower()
   ...:     d[word][tag] += 1

现在d将是:

In [6]: for word, word_data in d.items():
    ...:     for tag, count in word_data.items():
    ...:         print(word, tag, count)
    ...:         
('boy', 'NN', 1)
('short', 'NNP', 1)
('on', 'IN', 1)
('david', 'NNP', 1)
('will', 'MD', 1)
('sits', 'VBZ', 1)
('chair', 'VB', 1)
('chair', 'NN', 1)
('.', '.', 2)
('meeting', 'NN', 1)
('the', 'DT', 3)

相关问题 更多 >