输入一段英文,用python函数实现统计单词个数;统计标点符号个数;将每个单词逆序,统计字母出现的频率,返回字典等功能
时间: 2023-08-14 18:04:32 浏览: 120
Python实现统计单词出现的个数
可以使用Python的内置函数和模块来实现这些功能。
1. 统计单词个数和标点符号个数
```python
import string
def count_words(text):
"""
统计单词个数和标点符号个数
"""
words = text.split()
num_words = len(words)
num_punctuations = sum([1 for char in text if char in string.punctuation])
return num_words, num_punctuations
```
2. 将每个单词逆序
```python
def reverse_words(text):
"""
将每个单词逆序
"""
words = text.split()
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words)
```
3. 统计字母出现的频率,返回字典
```python
def count_letters(text):
"""
统计字母出现的频率,返回字典
"""
freq_dict = {}
for char in text:
if char.isalpha():
if char.lower() in freq_dict:
freq_dict[char.lower()] += 1
else:
freq_dict[char.lower()] = 1
return freq_dict
```
完整代码如下:
```python
import string
def count_words(text):
"""
统计单词个数和标点符号个数
"""
words = text.split()
num_words = len(words)
num_punctuations = sum([1 for char in text if char in string.punctuation])
return num_words, num_punctuations
def reverse_words(text):
"""
将每个单词逆序
"""
words = text.split()
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words)
def count_letters(text):
"""
统计字母出现的频率,返回字典
"""
freq_dict = {}
for char in text:
if char.isalpha():
if char.lower() in freq_dict:
freq_dict[char.lower()] += 1
else:
freq_dict[char.lower()] = 1
return freq_dict
text = "Hello World! This is a sample text for testing purposes."
num_words, num_punctuations = count_words(text)
print("Number of words:", num_words)
print("Number of punctuations:", num_punctuations)
reversed_text = reverse_words(text)
print("Reversed words:", reversed_text)
freq_dict = count_letters(text)
print("Letter frequency:", freq_dict)
```
阅读全文