python - 如何使用 pywsd.utils 对 .txt 文件而不是句子进行词形还原?
问题描述
我对 Python 很陌生,我尝试学习基本的文本分析、主题建模等。
我编写了以下代码来清理我的文本文件。与 NLTK 的 WordNetLemmatizer() 相比,我更喜欢 pywsed.utils lemmatize.sentence() 函数,因为它可以生成更清晰的文本。以下代码适用于句子:
from nltk.corpus import stopwords
from pywsd.utils import lemmatize_sentence
import string
s = "Dew drops fall from the leaves. Mary leaves the room. It's completed. Hello. This is trial. We went home. It was easier. We drank tea. These are Demo Texts. Right?"
lemm = lemmatize_sentence(s)
print (lemm)
stopword = stopwords.words('english') + list(string.punctuation)
removingstopwords = [word for word in lemm if word not in stopword]
print (removingstopwords, file=open("cleaned.txt","a"))
但是我没有做的是对目录中的原始文本文件进行词形还原。我猜 lemmatize.sentence() 只需要字符串?
我设法读取文件的内容
with open ('a.txt',"r+", encoding="utf-8") as fin:
lemm = lemmatize_sentence(fin.read())
print (lemm)
但是这次代码未能删除一些关键字,如“n't”、“'ll”、“'s”或“'”,以及导致文本未清理的标点符号。
1)我做错了什么?我应该先标记化吗?(我也未能提供 lemmatize.sentence() 的结果)。
2)如何获得没有任何格式的输出文件内容(没有单引号和括号的单词)?
任何帮助是极大的赞赏。提前致谢。
解决方案
只需将 lemmatize 逐一应用于每一行,然后将其附加到带有新行的字符串。所以本质上,它在做同样的事情。除了做每一行,将它附加到一个临时字符串并用新行分隔每一行,然后在最后我们打印出临时字符串。您可以在最后使用临时字符串作为最终输出。
my_temp_string = ""
with open ('a.txt',"r+", encoding="utf-8") as fin:
for line in fin:
lemm = lemmatize_sentence(line)
my_temp_string += f'{lemm} \n'
print (my_temp_string)
推荐阅读
- ansible - 如何在ansible中从stdout.lines中提取准确的输出
- java - jdbcTemplate batchUpdate 正在抛出 java.lang.ClassCastException:java.util.ArrayList 无法强制转换
- python - 路径函数在 python IDLE 和 google colab 中的工作方式是否不同?
- python - 阻止 pandas 静默转换超过 dtype 限制的数字
- excel - 导出到复制的文件
- python - 在 GF(5^2) 上创建多项式环时引发错误
- c# - 搜索特定行时未处理的 GridView 触发事件 RowEditing
- webpack - webpack 开发服务器“不是来自 webpack 的内容来自”
- css - 使用 CSS 对相同的动态 HTML 元素进行分组
- c# - 具有数据库读取的多线程应用程序 - 每个线程唯一的记录