python - 不确定如何将处理后的文本写入具有原始文件名的新目录
问题描述
我可以将单个文件写入不同的目录,但是当我尝试遍历目录中的所有文件时,我不知道如何编写处理过的文件。
我已经查看了将 for 循环与 glob 和 os 模块一起使用的示例,但我无法使其适用于我的特定目的。如果有帮助,我可以包含处理发生的代码。
for filename in glob.glob(os.path.join('*.txt')):
with open(filename,'r', encoding='utf-8', errors='ignore') as file:
words = file.read()
processedwords = lemmatize_words(words)
file = open(filename, 'w')
file.write(processedwords)
我期待文件写入目录。这是返回一个列表。我需要将词形还原的单词保存为其原始文件名。
C:\Users\Administrator\Desktop\Python Assignments>python readwrite.py
Traceback (most recent call last):
File "readwrite.py", line 88, in <module>
file.write(processedwords)
TypeError: write() argument must be str, not list
解决方案
让我更正你的代码
for filename in glob.glob(os.path.join('*.txt')):
with open(filename,'r', encoding='utf-8', errors='ignore') as file:
words = file.read()
processedwords = str(lemmatize_words(words)) #change class of lemmatize_words(words)
file = open(filename, 'w')
file.write(processedwords)
问题是lemmatize_words(words)
返回一个非字符串值,因此您必须使用str
类将其更改为字符串值。因为processedwords
不是字符串类型
推荐阅读
- java - 从 firebase 添加数据会导致无限循环
- android - recyclerview 适配器的不同实例具有相同的变量值
- tensorflow - 使用 Tensorflow 2.1.0 运行 TensorBoard 调试插件
- c++ - 运行时在构造函数中初始化向量类成员——C++
- c# - 使用 Cognito 和 Xamarin 表单的 Google 身份验证
- python - 在 Python 中将信息从一个线程发送到另一个线程并在原始线程、PyQT、MVC 架构中显示消息
- docker - 用 API 网关大使替换 nginx 入口
- java - 映射 get/customers 时出现 404 错误
- c# - 如何为 ThisDocument 声明一个基类?
- mysql - MYSQL:使用 SELECT 和多个 JOINS 更新数据库行