1

在阅读了 Peter Norvig 的How to write a spelling Corrector之后,我尝试让代码适用于波斯语。我重写了这样的代码:

import re, collections

def normalizer(word):
    word = word.replace('ي', 'ی')
    word = word.replace('ك', 'ک')
    word = word.replace('ٔ', '')
    return word

def train(features):
    model = collections.defaultdict(lambda: 1)
    for f in features:
        model[f] += 1
    return model

NWORDS = train(normalizer(open("text.txt", encoding="UTF-8").read()))

alphabet = 'ا آ ب پ ت ث ج چ ح خ د ذ ر ز س ش ص ض ط ظ ع غ ف ق ک گ ل م ن و ه ی ء'

在 Norvig 的原始代码中,NWORDS 是记录单词及其在文本中出现次数的字典。我试图print (NWORDS)看看它是否适用于波斯字符,但结果无关紧要。它不计算单词,它计算单独字母的出现。

有谁知道代码哪里出错了?

PS 'text.txt' 实际上是波斯文本的长连接,就像 Norvig 代码中的等价物一样。

4

1 回答 1

1

您正在申请normalizer文件对象。

我怀疑你真的想做这样的事情

with open('text.txt') as fin:
    Nwords = trian(normalizer(word) for ln in fin for word in ln.split()))

我也会考虑使用Counter http://docs.python.org/2/library/collections.html#collections.Counter

于 2013-10-26T02:07:44.693 回答