从单词和词性生成多级词典

时间:2016-10-18 16:15:48

标签: python regex dictionary part-of-speech

鉴于Penn Treebank以这种格式标记了一些文本:

" David / NNP Short / NNP将/ MD主席/ VB / DT会议/ NN ./。 / DT boy / NN将/ VBZ置于/ DT / DT主席/ NN ./."

我想制作一个多级字典,其中包含单词作为键,并计算它标记为每个POS的频率,因此我们有['主席,VB:1,NN:1' ,' The,DT:3',]等

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

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

但是不能弄清楚如何将它们放在一起来为一个单词及其相应的POS出现创建条目。

思想?

1 个答案:

答案 0 :(得分:2)

在这种情况下,您不必使用正则表达式。

您可以做的是按空格分割,然后通过斜线将结果收集到defaultdict int 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 中:{/ p>

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) 将是:

psexec \\@agents.txt -s reg query "HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer" /v svcVersion >test.txt