python :getting the count for the adjectives in a string

标签 python counter nltk

<分区>

我有一个字符串 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})

关于 python :getting the count for the adjectives in a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32724867/

相关文章:

python - Matplotlib 中 3-D 散点图中的 z 轴缩放和限制

python - 无法使用 process.kill() 或 process.terminate() 或 os.kill() 或使用 psutil 终止 Python 子进程

Python:将计数器写入 csv 文件

python - 我有一个印地文 wordnet 数据库和 API。我想从 NLTK python 访问这个 wordnet。有没有办法将我们自己的wordnet添加到NLTK中?

python - 如何能够以一定的字符串长度添加字符(Python)?

python - Django-注册。发送的激活链接缺少我的应用名称

javascript - 在递归函数调用中递增计数器

python - 如何按值对计数器进行排序? - Python

python-3.x - 从一个单词中获取所有可能的 pos 标签

python - NLTK 只搜索名词同义词集