编写一个程序,从键盘读入一段英文(多行),找出其中所有的英文单词,数统计每个单词出现的次,并按照单词出现次数由大到小排序后输出。
时间: 2024-05-01 08:17:06 浏览: 11
这是一个比较复杂的程序,需要用到字符串处理和数据结构。下面是一个可能的实现方案:
```python
import re
# 读入文本
text = ""
while True:
line = input()
if line == "":
break
text += line + "\n"
# 提取单词
words = re.findall(r"\b\w+\b", text)
# 统计单词出现次数
count = {}
for word in words:
count[word] = count.get(word, 0) + 1
# 按照出现次数排序
sorted_words = sorted(count.items(), key=lambda x: x[1], reverse=True)
# 输出结果
for word, cnt in sorted_words:
print(word, cnt)
```
这个程序使用了正则表达式来提取单词,使用了字典来统计单词出现次数,使用了列表排序来按照出现次数排序。注意,这个程序没有考虑大小写问题,即"Hello"和"hello"被视为不同的单词。如果需要考虑大小写问题,可以将所有单词转换为小写字母再进行统计。
相关问题
用Java代码编写一个程序,键盘读入一行数字,统计各数字出现次数
好的,以下是Java代码实现:
```java
import java.util.*;
public class NumberCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一行数字:");
String input = scanner.nextLine();
scanner.close();
Map<Character, Integer> countMap = new HashMap<>();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isDigit(c)) {
countMap.put(c, countMap.getOrDefault(c, 0) + 1);
}
}
System.out.println("各数字出现次数为:");
for (char c : countMap.keySet()) {
System.out.println(c + ": " + countMap.get(c));
}
}
}
```
这个程序首先通过键盘读入一行数字,然后使用 HashMap 统计每个数字出现的次数,最后输出结果。需要注意的是,这里使用了 `Character.isDigit` 方法判断一个字符是否为数字。
用Java代码编写一个程序,键盘读入一行数字,用空格隔开,统计各数字出现次数
好的,以下是Java代码实现:
```java
import java.util.*;
public class NumberCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一行数字,用空格隔开:");
String input = scanner.nextLine();
scanner.close();
Map<Integer, Integer> countMap = new HashMap<>();
String[] nums = input.split(" ");
for (String num : nums) {
try {
int n = Integer.parseInt(num);
countMap.put(n, countMap.getOrDefault(n, 0) + 1);
} catch (NumberFormatException e) {
// 如果输入的不是数字,忽略掉
}
}
System.out.println("各数字出现次数为:");
for (int n : countMap.keySet()) {
System.out.println(n + ": " + countMap.get(n));
}
}
}
```
这个程序首先通过键盘读入一行数字,然后使用空格分割成一个个数字,再使用 HashMap 统计每个数字出现的次数,最后输出结果。需要注意的是,这里使用了 `Integer.parseInt` 方法将字符串转换成整数,如果转换失败则忽略掉该字符串。