我想为我的语言模型计算条件概率分布,但是我不能这样做,因为我需要条件频率分布,这是我无法生成的。这是我的密码:
# -*- coding: utf-8 -*-
import io
import nltk
from nltk.util import ngrams
from nltk.tokenize import sent_tokenize
from preprocessor import utf8_to_ascii
with io.open("mypet.txt",'r',encoding='utf8') as utf_file:
file_content = utf_file.read()
ascii_content = utf8_to_ascii(file_content)
sentence_tokenize_list = sent_tokenize(ascii_content)
all_trigrams = []
for sentence in sentence_tokenize_list:
sentence = sentence.rstrip('.!?')
tokens = nltk.re.findall(r"\w+(?:[-']\w+)*|'|[-.(]+|\S\w*", sentence)
trigrams = ngrams(tokens, 3,pad_left=True,pad_right=True,left_pad_symbol='<s>', right_pad_symbol="</s>")
all_trigrams.extend(trigrams)
conditional_frequency_distribution = nltk.ConditionalFreqDist(all_trigrams)
conditional_probability_distribution = nltk.ConditionalProbDist(conditional_frequency_distribution, nltk.MLEProbDist)
for trigram in all_trigrams:
print "{0}: {1}".format(conditional_probability_distribution[trigram[0]].prob(trigram[1]), trigram)但是我发现了一个错误:
line 23, in <module>
ValueError: too many values to unpack这是我的preprocessor.py文件,它处理utf-8字符:
# -*- coding: utf-8 -*-
import json
def utf8_to_ascii(utf8_text):
with open("utf_to_ascii.json") as data_file:
data = json.load(data_file)
utf_table = data["chars"]
for key, value in utf_table.items():
utf8_text = utf8_text.replace(key, value)
return utf8_text.encode('ascii')这是我的utf_to_ascii.json文件,用于将utf-8 char替换为ascii char:
{
"chars": {
"“":"",
"”":"",
"’":"'",
"—":"-",
"–":"-"
}
}有人能建议我如何计算NLTK中三角图的条件频率分布吗?
发布于 2016-12-09 12:22:54
我终于想出了怎么做。因此,在上面的代码中,我是,将trigram转换为bigram。例如,我有('I', 'am', 'going'),正在将其转换为(('I', 'am'), 'going')。这是一个有两个元组的双元组,其中第一个元组又是两个单词的元组。为了达到这个目的,我只修改了几行代码:
trigrams_as_bigrams = []
for sentence in sentence_tokenize_list:
....
....
trigrams = ngrams(tokens, 3,pad_left=True,pad_right=True,left_pad_symbol='<s>', right_pad_symbol="</s>")
trigrams_as_bigrams.extend([((t[0],t[1]), t[2]) for t in trigrams])
....
....剩下的代码和以前一样。对我来说很好。谢谢你的努力。
https://stackoverflow.com/questions/41057816
复制相似问题