我有一个字符串
s=“X 先生很棒。他很棒。Y 先生也很棒。”
我需要从字符串中提取所有形容词以及每个形容词的数量。例如
该字符串包含形容词“awesome”、“amazing”,其中 2 表示 awesome,1 表示 amazing。
为了提取形容词,我使用了 NLTK。这是提取形容词的代码,
adjectives =[token for token, pos in nltk.pos_tag(nltk.word_tokenize(b)) if pos.startswith('JJ')]
我需要代码为字符串中的每个形容词获取一个计数器。
它应该像
形容词:反对
您可以使用 collections.Counter
:
>>> from collections import Counter
>>> adjectives = ['awesome', 'amazing', 'awesome']
>>> counts = Counter(adjectives)
>>> counts.items()
[('awesome', 2), ('amazing', 1)]
如果你愿意,可以将其转换为字典:
>>> dict(counts.items())
{'amazing': 1, 'awesome': 2}
或者您可以访问键和值:
>>> for key in counts.keys():
... print key, counts.get(key)
awesome 2
amazing 1
编辑:
对于列表列表,您需要flatten the lists :
>>> adjectives = [['awesome', 'amazing'], ['good', 'nice' ]]
>>> counts = Counter(adjective
... for group in adjectives
... for adjective in group)
>>> counts
Counter({'awesome': 1, 'good': 1, 'amazing': 1, 'nice': 1})
或使用 itertools.chain.from_iterable
:
>>> from itertools import chain
>>> Counter(chain.from_iterable(adjectives))
Counter({'awesome': 1, 'good': 1, 'amazing': 1, 'nice': 1})