输入一串文本,统计其中出现的词频(词的个数),并按字典序输出。 输入示例: I am a teacher 输出://输出格式:词和数字间空一格,数字后无空格 I 1 am 1 a 1 teacher 1
时间: 2023-06-14 07:05:56 浏览: 42
好的,可以使用Python来实现。以下是代码实现:
```python
text = input() # 获取输入文本
words = text.split() # 将文本按空格分割成单词列表
freq = {} # 存储每个单词出现的次数
for word in words:
freq[word] = freq.get(word, 0) + 1 # 如果单词已出现过,则将计数器加1;否则将计数器初始化为1
# 按字典序排序并输出结果
for word in sorted(freq):
print(word, freq[word])
```
使用示例:
```
输入:I am a teacher
输出://输出格式:词和数字间空一格,数字后无空格
I 1
a 1
am 1
teacher 1
```
相关问题
c++输入一串文本,统计其中出现的词频(词的个数),并按字典序输出。 输入示例: I am a teacher 输出://输出格式:词和数字间空一格,数字后无空格 I 1 am 1 a 1 teacher 1
以下是一个简单的实现:
```cpp
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <cctype>
using namespace std;
int main() {
string text;
getline(cin, text);
map<string, int> freq_map;
// 将文本转换为小写字母形式,方便统计词频
transform(text.begin(), text.end(), text.begin(), ::tolower);
// 分割文本并统计词频
string word;
for (int i = 0; i < text.size(); i++) {
if (isalpha(text[i])) {
word += text[i];
} else {
if (word != "") {
freq_map[word]++;
word = "";
}
}
}
if (word != "") {
freq_map[word]++;
}
// 按字典序输出
for (auto it = freq_map.begin(); it != freq_map.end(); it++) {
cout << it->first << " " << it->second << endl;
}
return 0;
}
```
其中,`map` 类型用于存储词频信息,`transform` 函数用于将文本转换为小写字母形式,`isalpha` 函数用于判断字符是否为字母。
编写程序统计一个英文文本文件中每个单词的出现次数(词频统计),并将统计结果按单词字典序输出到屏幕上。
好的,可以使用 Python 编写程序来实现该功能。以下是一个示例代码:
```python
import re
# 读取文本文件
with open('example.txt', 'r') as f:
text = f.read()
# 将所有非单词字符替换为空格
text = re.sub(r'\W+', ' ', text)
# 将文本转换为小写
text = text.lower()
# 将文本分割为单词列表
words = text.split()
# 统计每个单词出现的次数
word_count = {}
for word in words:
if word not in word_count:
word_count[word] = 0
word_count[word] += 1
# 按单词字典序排序并输出结果
sorted_words = sorted(word_count.keys())
for word in sorted_words:
print(word, word_count[word])
```
在上面的代码中,我们使用正则表达式将所有非单词字符替换为空格,然后将文本转换为小写,最后将文本分割为单词列表。接着,我们使用一个字典来统计每个单词出现的次数。最后,我们按单词字典序排序并输出结果。
你可以将上述代码保存为一个 Python 文件,并将需要统计的英文文本文件放在与该 Python 文件同一目录下,然后在命令行中运行该 Python 文件即可。