文件夹中的txt文本全部导入 python

循环导入文件夹中txt文本

循环将文件夹中的txt文本全部导入

import os
rootdir = 'F:/python_test/text/test'
list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
for i in range(0,len(list)):
	path = os.path.join(rootdir,list[i])
	if os.path.isfile(path):
		print(path)
可以使用类似于上面的代码进行批量处理。具体步骤如下: 1. 导入需要的库 ```python import os import jieba from nltk.corpus import stopwords ``` 2. 加载停用词表 ```python stopwords = stopwords.words('chinese') ``` 3. 定义处理函数 ```python def process_file(input_file, output_file): # 读取文本数据 with open(input_file, 'r', encoding='utf-8') as fin: text = fin.read() # 使用jieba分词进行分词操作 words = jieba.cut(text) # 去除停用词 result = [] for word in words: if word not in stopwords: result.append(word) # 将结果写入新的文件 with open(output_file, 'w', encoding='utf-8') as fout: fout.write(' '.join(result)) ``` 该函数接受两个参数:输入文件和输出文件。函数内部使用`jieba.cut()`函数进行分词操作,并去除停用词,然后将结果写入新的文件。 4. 遍历文件夹并进行处理 ```python # 定义输入和输出文件夹 input_folder = '/path/to/input/folder' output_folder = '/path/to/output/folder' # 遍历文件夹中的所有文件 for filename in os.listdir(input_folder): # 构造输入和输出文件的路径 input_file = os.path.join(input_folder, filename) output_file = os.path.join(output_folder, filename) # 处理文件 process_file(input_file, output_file) ``` 该代码段中,需要将`/path/to/input/folder`替换为实际的输入文件夹路径,将`/path/to/output/folder`替换为实际的输出文件夹路径。然后使用`os.listdir()`函数遍历输入文件夹中的所有文件,构造输入和输出文件的路径,并调用`process_file()`函数进行处理。 完整代码如下: ```python import os import jieba from nltk.corpus import stopwords # 加载中文停用词表 stopwords = stopwords.words('chinese') # 定义处理函数 def process_file(input_file, output_file): # 读取文本数据 with open(input_file, 'r', encoding='utf-8') as fin: text = fin.read() # 使用jieba分词进行分词操作 words = jieba.cut(text) # 去除停用词 result = [] for word in words: if word not in stopwords: result.append(word) # 将结果写入新的文件 with open(output_file, 'w', encoding='utf-8') as fout: fout.write(' '.join(result)) # 定义输入和输出文件夹 input_folder = '/path/to/input/folder' output_folder = '/path/to/output/folder' # 遍历文件夹中的所有文件 for filename in os.listdir(input_folder): # 构造输入和输出文件的路径 input_file = os.path.join(input_folder, filename) output_file = os.path.join(output_folder, filename) # 处理文件 process_file(input_file, output_file) ``` 注意,上面的代码中使用的是`utf-8`编码读写文件,如果输入文件的编码不是`utf-8`,需要根据实际情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值