写个一百行python代码实现简单功能
时间: 2023-08-10 08:36:05 浏览: 54
好的,这里提供一个简单的 Python 代码示例,该示例可以实现将一段英文文本中的单词进行统计,并按照出现次数从多到少进行排序输出。
```
import re
def count_words(text):
"""统计单词数量"""
words = re.findall(r'\b\w+\b', text.lower())
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
return word_counts
def sort_words(word_counts):
"""按照单词出现次数排序"""
sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
return sorted_words
def print_words(sorted_words):
"""输出单词及其出现次数"""
for word, count in sorted_words:
print(word, ':', count)
text = """
Python is a widely used high-level programming language for general-purpose programming,
created by Guido van Rossum and first released in 1991. An interpreted language, Python
has a design philosophy that emphasizes code readability (notably using whitespace
indentation to delimit code blocks rather than curly brackets or keywords), and a syntax
that allows programmers to express concepts in fewer lines of code than might be possible
in languages such as C++ or Java. The language provides constructs intended to enable
clear programs on both a small and large scale.
"""
word_counts = count_words(text)
sorted_words = sort_words(word_counts)
print_words(sorted_words)
```
这段代码首先定义了三个函数:`count_words()`、`sort_words()` 和 `print_words()`。`count_words()` 函数会统计文本中每个单词的出现次数,并返回一个字典类型的结果。`sort_words()` 函数会对单词出现次数进行排序,并返回一个列表类型的结果。`print_words()` 函数会输出单词及其出现次数。
在主程序中,我们定义了一个英文文本字符串 `text`,然后调用 `count_words()` 函数统计单词出现次数,再调用 `sort_words()` 函数对单词出现次数进行排序,最后调用 `print_words()` 函数输出单词及其出现次数。这样就完成了对一段英文文本中单词的统计和排序输出。
希望这个示例能够帮助您更好地理解 Python 语言的基本语法和操作。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)