NLP实验二
这个实验的环境安装还是有点离谱的,python版本必须是3.8的特定版本且还有一系列离谱的包环境配置,很让人抓狂啊,那接下来我们将通过图文流来解决这个实验!!
实验目标
实现通过调用微软语料库进行语料库训练来实现对句子语法"的 地 得"的语法判别
环境配置
过程太复杂了,我这里直接给打包好的环境:实验环境包
点击实验环境包的链接下载安装即可,但是这里有个细节要注意一哈,检查你已经安装好的python版本,如果有python版本是python3.8的那请你先去控制面板吧python3.8给卸载了,因为环境包里面自带了python3.8,如果你本身已经加了python3.8会撞掉的,如果原先电脑上没有python3.8那么请忽略!
实验配置
首先我们点击pycharm的设置按钮:
点击设置之后,我们找到我们当前项目下的python解释器按钮,然后我们点击添加本地解释器
点开本地解释器之后我们点击系统解释器,我们要把刚刚下好的环境包的python3.8环境导入解释器。
然后我们点击上图画圈的三个小点点之后,点击之后我们去找到刚刚下载好的环境包的python3.8的位置,默认位置在:
C:\Python38\python.exe
, 你要是嫌麻烦直接复制我这个路径即可。然后我们点击确定即可。
最后我们切换会python解释器页面看看是不是如上图所示已经变成了在
C:\Python38\python.exe
路径下的python3.8解释器,是的话我们就进入下一步,不是的话你自求多福,或者你联系我们站长---被杀戮的咸鱼。
实验代码
以上环境配置配置完成后我们在实验代码文件N_gram语法纠错.py(这个文件随便你定,只要是个py文件就好了)中输入:
import re
import numpy as np
from pyhanlp import *
import time
# 设置数据路径和模型保存路径
corpus_file = "msr_training.utf8"
model_destination = "msr_correction_model"
# 加载语料库,为每个未标注的词设置默认标签 "x"
SentenceList = SafeJClass('com.hankcs.hanlp.corpus.document.CorpusLoader').convert2SentenceList(corpus_file)
for sentence in SentenceList:
for token in sentence:
if token.label is None:
token.setLabel("x")
# 开始训练模型
start_time = time.time()
NatureDictionaryMaker = SafeJClass('com.hankcs.hanlp.corpus.dictionary.NatureDictionaryMaker')()
NatureDictionaryMaker.compute(SentenceList)
NatureDictionaryMaker.saveTxtTo(model_destination)
end_time = time.time()
print("2-gram training completed in {:.2f} seconds".format(end_time - start_time))
# 更新HanLP配置
HanLP.Config.CoreDictionaryPath = model_destination + ".txt"
HanLP.Config.BiGramDictionaryPath = model_destination + ".ngram.txt"
# 懒加载核心字典和二元词表字典
CoreDict = LazyLoadingJClass('com.hankcs.hanlp.dictionary.CoreDictionary')
BiGramDict = LazyLoadingJClass('com.hankcs.hanlp.dictionary.CoreBiGramTableDictionary')
# 定义计算权重的函数
def compute_weight(previous, candidate, next_word):
with open(model_destination + ".txt", 'r', encoding='utf-8') as file:
total_lines = len(file.readlines())
if CoreDict.getTermFrequency(candidate) > 0:
weight = (BiGramDict.getBiFrequency(previous, candidate) *
BiGramDict.getBiFrequency(candidate, next_word)) / (
CoreDict.getTermFrequency(candidate) * total_lines)
else:
weight = 0
return weight
# 测试候选词
candidates = ['的', '地', '得']
with open('的地得词组练习.txt', 'r', encoding='utf-8') as file:
content = file.readlines()
# 逐行处理
for item in content:
if item:
prev, correct, next_part = re.split('【|】', item.strip()) # Split and remove spaces
weights = [compute_weight(prev, word, next_part) for word in candidates]
prediction = candidates[np.argmax(weights)]
print(f"{'正确' if prediction == correct else '错误'}:{prediction} {item.strip()}")
最后我们执行这个实验代码文件即可!!!
停留在世界边缘,与之惜别