编写程序从键盘输入字符串,按字符出现频率的降序打印字母。
时间: 2023-05-26 16:07:42 浏览: 41
```
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
int main()
{
std::string str;
std::getline(std::cin, str);
std::map<char, int> freq_map;
for (char ch : str)
{
if (std::isalpha(ch)) // 只统计字母
{
freq_map[ch]++;
}
}
std::vector<std::pair<char, int>> freq_vec(freq_map.begin(), freq_map.end());
std::sort(freq_vec.begin(), freq_vec.end(), [](const auto& lhs, const auto& rhs) {
return lhs.second > rhs.second; // 按频率降序排序
});
for (const auto& pair : freq_vec)
{
std::cout << pair.first << " : " << pair.second << std::endl;
}
return 0;
}
```
相关问题
用python编写程序实现接收字符串并按字符出现频率的降序打印字母
好的,这个问题可以用 Python 中的字典来解决。你可以使用 collections 模块中的 Counter 类来统计字符串中各个字符出现的次数,然后按照出现次数进行降序排列。
下面是一个示例代码:
```python
from collections import Counter
def print_char_by_freq(input_str):
# 统计字符出现次数
char_count = Counter(input_str)
# 按照出现次数降序排列
sorted_char_count = sorted(char_count.items(), key=lambda item: item[1], reverse=True)
# 打印结果
for char, count in sorted_char_count:
print(char, count)
# 测试代码
input_str = "hello world"
print_char_by_freq(input_str)
```
输出结果为:
```
l 3
o 2
h 1
e 1
1
w 1
r 1
d 1
```
代码说明:
1. 首先导入 collections 模块中的 Counter 类。
2. 定义一个函数 `print_char_by_freq`,接受一个字符串参数。
3. 使用 Counter 对象统计字符串中各个字符出现的次数,得到一个字典对象 `char_count`。
4. 使用 sorted 函数对字典对象中的键值对进行排序,按照值进行降序排列,得到一个列表对象 `sorted_char_count`。
5. 遍历排序后的列表对象,依次输出每个字符和对应的出现次数。
python文本字符分析。编写程序接收字符串,按照字符出现频率降序打印字母
好的,对于您的问题,我可以给出以下Python代码示例来实现所需的文本字符分析功能:
```python
string = input("请输入要分析的字符串:") # 接收用户输入的字符串
freq = {}
for char in string:
if char.isalpha(): # 只统计字母出现次数
if char in freq:
freq[char] += 1
else:
freq[char] = 1
sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
for item in sorted_freq:
print(item[0], ":", item[1])
```
您可以直接复制上述代码并在Python环境中运行,用您自己的测试字符串代替`input`函数接收的字符串即可。该程序会输出每个出现过的字母以及它们在文本中出现的次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)