在这种情况下,您不必使用正则表达式。
您可以做的是按空格拆分,然后通过斜线将结果收集到defaultdict
ofdefaultdict
中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
现在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)