-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path总结.txt
47 lines (36 loc) · 2.01 KB
/
总结.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
》》写一个python程序,实现以下步骤:
1.使用utf-8编码读取当前目录下chapter文件夹中的第一个txt文件
2.导入“api”包,把读取到的文字输入“api.summarize()”函数,如果函数报错,打印正在读取的文件的文件名并跳过第3步
3.把“api.summarize()”函数返回的字符用utf-8编码以相同文件名保存到当前目录的summarize文件夹
4.重复以上3步,完成对当前目录下chapter文件夹中所有txt文件的读取
》
```python
import os
import glob
# 假设api包已经安装并且包含summarize函数
import api
def process_files(chapter_folder, summarize_folder):
# 确保summarize文件夹存在
if not os.path.exists(summarize_folder):
os.makedirs(summarize_folder)
# 获取chapter文件夹中所有的txt文件
txt_files = glob.glob(os.path.join(chapter_folder, '*.txt'))
for txt_file in txt_files:
try:
# 读取文件内容
with open(txt_file, 'r', encoding='utf-8') as file:
content = file.read()
# 使用api.summarize()函数处理内容
summary = api.summarize(content)
# 获取文件名(不包括路径)
file_name = os.path.basename(txt_file)
# 保存摘要到summarize文件夹
summary_file_path = os.path.join(summarize_folder, file_name)
with open(summary_file_path, 'w', encoding='utf-8') as summary_file:
summary_file.write(summary)
except Exception as e:
print(f"Error processing file {txt_file}: {e}")
# 使用当前目录下的chapter文件夹和summarize文件夹
process_files('chapter', 'summarize')
```
这个程序会读取当前目录下`chapter`文件夹中的所有`.txt`文件,使用`api.summarize()`函数处理每个文件的内容,并将结果保存到`summarize`文件夹中。如果处理过程中发生错误,程序会打印错误信息并跳过当前文件的处理。