首页 > 解决方案 > 如何在 nltk 中预测 IBM 模型的翻译(解码)?

问题描述

我对 NLTK API 还很陌生,想开始使用简单的 IBM Model 1,它进行字级翻译。这是我到目前为止所做的,在NLTK API 文档的帮助下。

from nltk.translate.ibm1 import IBMModel1
from nltk.translate import AlignedSent

def get_text(filename):
    senteces = []
    with open(filename,'r') as f:
        for sentence in f:
            sentences.append(sentence.split())
    return sentences

src_sentences = get_text('source.txt')
trg_sentences = get_text('target.txt')

bitext = []
for i in range(len(src_sentences)):
    bitext.append(AlignedSent(src_sentences[i], trg_sentences[i]))

ibm1 = IBMModel1(bitext, 5)

现在IBMModel1已经创建了,我不确定如何执行解码,即。从测试集中预测翻译。我似乎也无法在文档中找到它。

简单来说,我想获得一个预测的翻译,给定一个使用这个模型的随机源句子。我如何实现这一目标?

标签: pythonnlpnltk

解决方案


请参阅https://www.nltk.org/api/nltk.translate.ibm1.html#nltk.translate.ibm1.IBMModel1上的这些示例

>>> bitext = []
>>> bitext.append(AlignedSent(['klein', 'ist', 'das', 'haus'], ['the', 'house', 'is', 'small']))
>>> bitext.append(AlignedSent(['das', 'haus', 'ist', 'ja', 'groß'], ['the', 'house', 'is', 'big']))
>>> bitext.append(AlignedSent(['das', 'buch', 'ist', 'ja', 'klein'], ['the', 'book', 'is', 'small']))
>>> bitext.append(AlignedSent(['das', 'haus'], ['the', 'house']))
>>> bitext.append(AlignedSent(['das', 'buch'], ['the', 'book']))
>>> bitext.append(AlignedSent(['ein', 'buch'], ['a', 'book']))

>>> ibm1 = IBMModel1(bitext, 5)

>>> print(ibm1.translation_table['buch']['book'])


推荐阅读