📅  最后修改于: 2023-12-03 15:34:14.209000             🧑  作者: Mango
Python字符串是最常用的数据类型之一。在Python中,我们可以使用单引号、双引号或三重引号来表示一个字符串。在这个Python字符串测验中,我们将探究一些有趣的字符串操作。在第18个问题中,我们将学习如何将字符串拆分为单词,并计算每个单词出现的次数。
编写一个Python程序,接受一个字符串作为输入,将其拆分为单词,并计算每个单词出现的次数。
text = "Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java."
| 单词 | 出现次数 |
| ----------- | --------- |
| Python | 2 |
| is | 1 |
| an | 1 |
| interpreted | 1 |
| high-level | 1 |
| general-purpose | 1 |
| programming | 1 |
| language | 1 |
| Created | 1 |
| by | 1 |
| Guido | 1 |
| van | 1 |
| Rossum | 1 |
| and | 1 |
| first | 1 |
| released | 1 |
| in | 2 |
| 1991 | 1 |
| design | 1 |
| philosophy | 1 |
| emphasizes | 1 |
| code | 1 |
| readability | 1 |
| its | 1 |
| syntax | 1 |
| allows | 1 |
| programmers | 1 |
| to | 1 |
| express | 1 |
| concepts | 1 |
| fewer | 1 |
| lines | 1 |
| of | 1 |
| than | 1 |
| would | 1 |
| be | 1 |
| possible | 1 |
| languages | 1 |
| such | 1 |
| as | 1 |
| C++ | 1 |
| or | 1 |
| Java | 1 |
def word_count(text):
# 将输入文本转换为小写形式
text = text.lower()
# 将文本分割成单词
words = text.split()
# 使用dictionary存储每个单词的出现次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 输出一个表格来显示每个单词和它的出现次数
print("| 单词 | 出现次数 |")
print("| --- | --- |")
for word, count in word_count.items():
print(f"| {word} | {count} |")
# 测试代码
text = "Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java."
word_count(text)
返回的markdown格式代码片段如下:
| 单词 | 出现次数 |
| ----------- | --------- |
| python | 2 |
| is | 1 |
| an | 1 |
| interpreted | 1 |
| high-level | 1 |
| general-purpose | 1 |
| programming | 1 |
| language | 1 |
| created | 1 |
| by | 1 |
| guido | 1 |
| van | 1 |
| rossum | 1 |
| and | 1 |
| first | 1 |
| released | 1 |
| in | 2 |
| 1991 | 1 |
| python's | 1 |
| design | 1 |
| philosophy | 1 |
| emphasizes | 1 |
| code | 1 |
| readability | 1 |
| its | 1 |
| syntax | 1 |
| allows | 1 |
| programmers | 1 |
| to | 1 |
| express | 1 |
| concepts | 1 |
| fewer | 1 |
| lines | 1 |
| of | 1 |
| than | 1 |
| would | 1 |
| be | 1 |
| possible | 1 |
| languages | 1 |
| such | 1 |
| as | 1 |
| c++ | 1 |
| or | 1 |
| java | 1 |