python 运用LTP4对txt文件进行分词并去除停用词,然后进行词频排序,并将结果保存为txt文件
时间: 2024-05-16 15:17:29 浏览: 11
好的,可以使用Python中的LTP4库来完成分词和去除停用词的操作,然后使用Counter类来进行词频统计和排序,最后将结果保存为txt文件。具体代码如下:
```python
import os
from collections import Counter
import pyltp
import codecs
# 加载LTP模型
LTP_DATA_DIR = 'ltp_data_v3.4.0' # LTP模型目录的路径
cws_model_path = os.path.join(LTP_DATA_DIR, 'cws.model') # 分词模型路径,模型名称为cws.model
pos_model_path = os.path.join(LTP_DATA_DIR, 'pos.model') # 词性标注模型路径,模型名称为pos.model
ner_model_path = os.path.join(LTP_DATA_DIR, 'ner.model') # 命名实体识别模型路径,模型名称为ner.model
parser_model_path = os.path.join(LTP_DATA_DIR, 'parser.model') # 依存句法分析模型路径,模型名称为parser.model
srl_model_path = os.path.join(LTP_DATA_DIR, 'pisrl.model') # 语义角色标注模型路径,模型名称为pisrl.model
segmentor = pyltp.Segmentor() # 初始化实例
segmentor.load(cws_model_path) # 加载分词模型
# 停用词列表
stopwords = []
with codecs.open('stopwords.txt', 'r', encoding='utf-8') as f:
for line in f:
stopwords.append(line.strip())
# 分词并去除停用词
with codecs.open('input.txt', 'r', encoding='utf-8') as f:
words = []
for line in f:
seg_list = segmentor.segment(line.strip()) # 分词
for word in seg_list:
if word not in stopwords:
words.append(word)
# 统计词频并排序
word_counts = Counter(words)
sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# 将结果保存为txt文件
with codecs.open('output.txt', 'w', encoding='utf-8') as f:
for item in sorted_word_counts:
f.write('{0}\t{1}\n'.format(item[0], item[1]))
# 释放模型
segmentor.release()
```
其中,停用词列表可以从网上下载或自行构建,这里假设已经存在名为`stopwords.txt`的文件。运行后,会将分词并去除停用词后的结果保存为`output.txt`文件。