统计一个指定字符串中每个字符出现的次数py
时间: 2023-05-30 22:07:16 浏览: 55
可以使用字典来进行统计:
```python
s = "hello world"
count = {}
for c in s:
if c in count:
count[c] += 1
else:
count[c] = 1
print(count)
```
输出:
```
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
```
也可以使用 `collections` 模块中的 `Counter` 类来进行统计:
```python
from collections import Counter
s = "hello world"
count = Counter(s)
print(count)
```
输出:
```
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
```
相关问题
输入一个字符串,统计该字符串在文件student.txt中出现的次数。
好的,我可以为您实现统计字符串在文件中出现次数的操作。以下是示例代码:
```python
text = input("请输入要统计出现次数的字符串:")
count = 0
with open("student.txt", "r") as f:
for line in f:
count += line.count(text)
print(f"字符串'{text}'在文件中出现了{count}次。")
```
以上代码中,我们首先使用input()函数获取用户输入的字符串,然后使用with语句打开一个名为"student.txt"的文本文件,并以只读模式("r")打开。接着,我们使用for循环遍历文件中的每一行,对每一行使用count()方法来统计字符串在该行中出现的次数,并将其累加到count变量中。最后,输出字符串在文件中出现的次数。
注意:以上代码中,我们假设文件中每一行都只包含一个字符串,如果一行中包含多个字符串,该代码会将每个字符串都计算在内。如果您需要精确地统计某个字符串在文件中出现的次数,请确保文件中每行只包含一个该字符串。
您可以将以上代码保存到一个.py文件中,运行后会提示用户输入要统计出现次数的字符串。完成后,程序会自动遍历文件并统计出该字符串在文件中出现的次数。
py统计字符串中词语位置和个数
可以使用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
```