You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python处理文件停用词后保存至新文件夹文件内容为空如何解决

解决方案

错误原因

  • 核心问题:生成过滤停用词后的词列表cleaned后,仅通过print()输出到控制台,未执行写入文件的操作,是文件为空的直接原因。
  • 文件句柄管理错误:未使用with上下文管理器管理写入文件的句柄,也没有主动调用关闭方法,即使补充写入逻辑,内容也会停留在缓冲区无法刷入磁盘。
  • 保存路径配置错误:当前save_dir指向corpus根目录,未指向目标Save-files文件夹,需要先调整路径并确保文件夹存在。
  • 路径拼接方式不规范:直接使用字符串拼接路径容易因斜杠匹配异常出错,推荐使用os.path.join处理路径拼接。

修复后代码

from nltk.corpus import stopwords
import os

stoplist = stopwords.words('english')

dir_path = 'C:/Users/Super/Desktop/IR/homework/Lab4/corpus/corpus/'
# 调整保存路径为Save-files文件夹
save_dir = "C:/Users/Super/Desktop/IR/homework/Lab4/corpus/Save-files/"
# 自动创建目标文件夹,已存在时不会报错
os.makedirs(save_dir, exist_ok=True)

for document in os.listdir(dir_path):
    # 用os.path.join拼接路径避免格式错误
    read_path = os.path.join(dir_path, document)
    save_path = os.path.join(save_dir, document)
    # 同时用with管理读写文件句柄,操作完成后自动关闭刷新内容
    with open(read_path, "r", encoding="utf-8") as reader, open(save_path, "w", encoding="utf-8") as writer:
        text = reader.read()
        cleaned = [word for word in text.split() if word not in stoplist]
        # 把词列表拼接为字符串后写入文件
        writer.write(' '.join(cleaned))

补充说明

如果你的源文件不是UTF-8编码,可以根据实际编码调整open方法中的encoding参数,避免读写时出现编码错误。

内容的提问来源于stack exchange,提问作者user14510391

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 16:06:04