对文本进行去除停用词,想要最后得出的结果存储在path1中,但是不知道应该怎么做操作了,求指教
你这代码好像问题挺多的,浅改一下:
import jieba
# 把结果存储到文本文件里好一点儿吧
path = 'sj.txt'
path1 = 'jg.txt'
stop_path = 'stopwords.txt'
f = open(path, encoding='utf-8')
fw = open(path1, 'w', encoding='utf-8')
for line in f.readlines(): # 要 readlines
constr = ''
for char in line:
# 1. 不能写 ord(char) in (xx, xx),没有这种写法;
# 2. 反了,应该是 not in。
if (ord(char) not in range(97, 123) and ord(char) not in range(65, 91)) or char == ' ':
constr += char
fw.write(constr)
# 关闭文件,更安全。
f.close()
fw.close()
f = open(path1, encoding='utf-8')
txt = f.read()
f.close()
words = jieba.lcut(txt)
stop_lines = open(stop_path, encoding='utf-8')
stopwords = [line.strip() for line in stop_lines.readlines()]
stop_lines.close()
sentences = ''
for word in words:
if word not in stopwords:
sentences += word
sentences += ' '
# 最后写入到 path1 里就行了
fw = open(path1, 'w', encoding='utf-8')
fw.write(sentences)
fw.close()
请供参考
文本去除停用词是 NLP 中的一个常见预处理步骤,它可以帮助我们将文本中一些常用但对文本特征提取没有帮助的无意义词语去掉,例如“的”、“啊”、“呢”等。在 Python 中,可以通过使用 NLTK(Natural Language Toolkit)库来进行中英文文本的停用词过滤。
以下是一个简单的 Python 代码示例,演示了如何使用 NLTK 去除英文文本中的停用词,并将结果存储到指定的路径中:
import nltk
from nltk.corpus import stopwords
# 加载停用词表
nltk.download('stopwords')
stop_words = set(stopwords.words('english'))
# 加载待处理的文本
text = "This is an example text to demonstrate how to remove stopwords from the text."
# 分词、去除停用词
tokens = nltk.word_tokenize(text)
filtered_tokens = [token for token in tokens if not token.lower() in stop_words]
# 将结果存储到指定文件
path1 = "path/to/filtered_text.txt"
with open(path1, mode="w", encoding="utf-8") as f:
f.write(" ".join(filtered_tokens))
上述代码首先加载了英语停用词表,然后读取了一个文本字符串,并使用 nltk.word_tokenize
函数将其分割为单词数组。随后,通过列表推导式和条件语句,过滤掉停用词,并得到被过滤后的单词数组。最后,将结果写入到指定路径的文件中,使用空格作为单词之间的分隔符。
如果您要处理其他语言(如中文)的文本,则需要选择相应的停用词表,并在分词时使用适当的工具库,例如中文分词器 jieba。此外,还需要注意不同语言的编码方式。
deactivate env_name
或者`activate root`切回root环境
Linux下:source deactivate