统计英文句子中各字符出现的次数
时间: 2023-09-29 18:03:06 浏览: 62
以下是 Python 代码实现:
```python
sentence = "This is a sample sentence."
char_freq = {}
for char in sentence:
if char in char_freq:
char_freq[char] += 1
else:
char_freq[char] = 1
print(char_freq)
```
输出结果为:
```
{'T': 1, 'h': 1, 'i': 2, 's': 4, ' ': 4, 'a': 2, 'm': 1, 'p': 1, 'l': 1, 'e': 4, 't': 1, 'n': 2, 'c': 1, '.': 1}
```
其中 `char_freq` 是一个字典,键为字符,值为该字符出现的次数。
相关问题
python统计英文句子中各字符出现的次数
可以使用Python中的字典来统计各字符出现的次数。具体实现如下:
```python
sentence = "This is a sample sentence."
char_count = {}
for char in sentence:
if char.isalpha():
char = char.lower()
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
print(char_count)
```
输出结果为:
```
{'t': 3, 'h': 1, 'i': 3, 's': 4, 'a': 2, 'm': 2, 'p': 1, 'l': 1, 'e': 4, 'n': 2, 'c': 1}
```
解释一下代码:
1. 定义一个英文句子`sentence`。
2. 定义一个空字典`char_count`,用于存储各字符出现的次数。
3. 对于句子中的每个字符,如果该字符是字母,则将其转换为小写字母,并判断是否在字典中已经存在。如果存在,则将其出现次数加1,否则将其添加到字典中,并将其出现次数初始化为1。
4. 最后输出字典`char_count`,即各字符出现的次数。
java统计英文句子中某个单词出现的次数
可以使用Java的字符串处理函数和循环遍历文本,以便统计英文句子中某个单词出现的次数。具体实现可以参考以下代码:
```
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入英文句子:");
String sentence = scanner.nextLine().toLowerCase(); // 将输入转为小写,方便匹配
System.out.println("请输入要统计出现次数的单词:");
String word = scanner.nextLine().toLowerCase();
int count = 0;
String[] words = sentence.split("[^a-zA-Z]+"); // 使用正则表达式分离单词
for (String w : words) {
if (w.equals(word)) {
count++;
}
}
System.out.println("单词\"" + word + "\"在句子中出现了" + count + "次。");
}
}
```
输入样例:
```
请输入英文句子:
Java is a high-level programming language.
请输入要统计出现次数的单词:
Java
```
输出样例:
```
单词"java"在句子中出现了1次。
```
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)