n = int(input()) file = open('step3/The Great Learning.txt', 'r', encoding='utf-8') #提示:可采用集合处理 #代码开始 #代码结束 file.close()
时间: 2024-01-16 20:03:14 浏览: 25
以下是代码的实现:
```
n = int(input())
file = open('step3/The Great Learning.txt', 'r', encoding='utf-8')
# 读取文本内容
text = file.read()
# 将文本内容转换为小写字母,去除标点符号和空格,并按照空格进行分割
words = set(text.lower().replace('\n', '').replace(',', '').replace('.', '').replace(';', '').replace('“', '').replace('”', '').replace(' ', '').split())
# 按照词频从高到低排序,并输出前n个词
for word, freq in sorted([(w, text.count(w)) for w in words], key=lambda x: x[1], reverse=True)[:n]:
print(word, freq)
file.close()
```
代码的实现步骤如下:
1. 读取文本文件`The Great Learning.txt`的内容并存储在变量`text`中。
2. 将文本内容转换为小写字母,去除标点符号和空格,并按照空格进行分割,得到每个单词。
3. 将单词存储在集合`words`中,以去除重复的单词。
4. 统计每个单词在文本中出现的频率,并按照词频从高到低排序。
5. 输出前n个频率最高的单词及其出现频率。
相关问题
#coding=utf-8 #输入n n = int(input()) with open('src/Step1/test.txt') as file_object: lines = file_object.readlines() # 请在此添加代码,实现编程要求 #********** Begin *********# #********** End **********#
以下是代码实现:
```python
n = int(input())
with open('src/Step1/test.txt') as file_object:
lines = file_object.readlines()
count = 0
for line in lines:
if line.strip() != "":
print(line.strip())
count += 1
if count == n:
break
```
首先读取文本文件中的所有行,并存储在列表 `lines` 中。然后遍历 `lines` 中的每一行,将非空行打印出来,并统计打印的行数。当打印的行数达到输入的行数 `n` 时,退出循环。注意要使用 `strip()` 方法去除每行字符串两端的空格和换行符。
c语言求和 sum = 1-1/2+1/3-1/4+...+1/99-1/100
以下是两种C语言求和的例子:
1.使用for循环
```c
#include <stdio.h>
int main() {
int n = 0;
int i = 0;
double flag = 1.0;//正负号改变的载体
double sum = 0.0;//注意结果需要浮点数
scanf("%d", &n);
for (i = 1; i <= n; i++) {
sum += flag * 1 / i;
flag = -flag;//借助循环进行正负号转化
}
printf("1-1/2+1/3...+1/99-1/100...=%lf", sum);
return 0;
}
```
2.使用while循环
```c
#include <stdio.h>
int main() {
int n = 0;
int i = 0;
double flag = 1.0;//正负号改变的载体
double sum = 0.0;//注意结果需要浮点数
scanf("%d", &n);
while(i<n) {
i++;
sum += flag * 1 / i;
flag = -flag;//借助循环进行正负号转化
}
printf("1-1/2+1/3...+1/99-1/100...=%lf", sum);
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)