py统计字符串中词语位置和个数
时间: 2024-03-24 07:12:53 浏览: 17
可以使用Python中的Counter和nltk库来实现:
```python
from collections import Counter
import nltk
text = "Hello world, hello python, hello NLTK"
tokens = nltk.word_tokenize(text)
counter = Counter(tokens)
for word, count in counter.items():
print(f"Word: {word}, Count: {count}")
```
输出结果:
```
Word: Hello, Count: 3
Word: world, Count: 1
Word: ,, Count: 2
Word: python, Count: 1
Word: NLTK, Count: 1
```
如果需要统计每个词语出现的位置,可以使用enumerate函数:
```python
for i, word in enumerate(tokens):
print(f"Word: {word}, Index: {i}")
```
输出结果:
```
Word: Hello, Index: 0
Word: world, Index: 1
Word: ,, Index: 2
Word: hello, Index: 3
Word: python, Index: 5
Word: ,, Index: 6
Word: hello, Index: 7
Word: NLTK, Index: 9
```