python统计每个单词出现的个数
时间: 2023-10-12 07:14:46 浏览: 200
你可以使用Python中的字典来实现统计每个单词出现的个数。首先,将文本转换为小写,并通过split()方法将其拆分为单词列表。然后,遍历单词列表并将每个单词添加到字典中。如果单词已经存在于字典中,则将其计数增加1。这里是一个示例代码:
```
text = "hello world hello"
word_list = text.lower().split()
word_count = {}
for word in word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count)
```
该代码将输出以下字典:
```
{'hello': 2, 'world': 1}
```
其中,'hello'出现了2次,'world'出现了1次。
相关问题
python统计单词的个数
要在Python中统计单词的个数,你可以按照以下步骤操作:
1. 输入一个英文句子,并以回车符结束。
2. 将句子按空格分隔成单词。
3. 创建一个空的字典来存储每个单词及其出现的次数。
4. 遍历分隔后的单词列表,对于每个单词,如果它已经在字典中,将对应的值加1;否则,在字典中添加该单词并将值设置为1。
5. 统计结束后,输出字典中的键值对,即每个单词及其出现的次数。
6. 输出字典的长度,即单词的个数。
以下是一个示例代码:
```python
sentence = input("请输入一个英文句子:")
words = sentence.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
for word, count in word_count.items():
print(word, ":", count)
print("单词的个数:", len(word_count))
```
用Python统计一个文本文字出现的个数
可以使用 Python 中的字典来统计一个文本中文字出现的个数,具体代码如下:
```python
text = "This is a test text. This text contains some repeated words like test and text."
word_count = {}
# 将文本按空格分割成单词
words = text.split()
# 遍历单词列表,统计每个单词出现的次数
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
# 打印每个单词出现的次数
for word, count in word_count.items():
print(f"{word}: {count}")
```
输出结果如下:
```
This: 2
is: 1
a: 1
test: 2
text.: 2
text: 1
contains: 1
some: 1
repeated: 1
words: 1
like: 1
and: 1
```
其中,`word_count` 是一个字典,存储了每个单词出现的次数。在遍历单词列表时,如果单词不在字典中,就将它加入字典并设置初始值为 1;否则,将它的计数加 1。最后,遍历字典并打印每个单词出现的次数。