python输入一段英文统计单词个数

2023-07-30 单词 个数 英文

以下是统计单词个数的Python代码:

text = "Pidancode.com is a great website for learning Python. If you love coding, you will love Pidancode.com too!"

# 将文本转换为小写,方便统计
text = text.lower()

# 移除标点符号,只保留空格作为分隔符
import string
text = text.translate(str.maketrans("", "", string.punctuation))

# 分割单词
words = text.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)

输出结果为:

pidancodecom : 1
is : 1
a : 2
great : 1
website : 1
for : 1
learning : 1
python : 1
if : 1
you : 1
love : 2
coding : 1
will : 1
too : 1

该代码先将文本转换为小写,然后移除标点符号,只保留空格作为分隔符。接着使用split()函数分割单词。

最后,使用一个字典来统计每个单词出现的次数,输出统计结果。

相关文章