如何在nltk-python中计算三元函数的条件概率分布和条件频率分布

2024-10-02 12:23:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为我的语言模型计算条件概率分布,但我做不到,因为我需要条件频率分布,我无法生成。这是我的代码:

# -*- 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)

但我得到了一个错误:

^{pr2}$

这是我的预处理器.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_ascii.json格式用于将utf-8字符替换为ascii字符的文件:

{
 "chars": {
          "“":"",
          "”":"",
          "’":"'",
          "—":"-",
          "–":"-"
 }
}

有人能建议我如何计算NLTK中三元组的条件频率分布?在


Tags: toimportasciicontentutf8allsentenceutf
1条回答
网友
1楼 · 发布于 2024-10-02 12:23:21

我终于想出了办法。所以在上面的代码中,我将把三元组转换成双元组。例如,我有('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])
....
....

其余代码和以前一样。对我来说很好。谢谢你的努力。在

相关问题 更多 >

    热门问题