已阅读 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)
来查看它是否适用于波斯语字符,但结果无关紧要。它不计算单词数,而是计算单独字母的出现次数。
有人知道代码哪里出了问题吗?
附注“text.txt”实际上是波斯语文本的长连接,就像 Norvig 代码中的等效内容一样。
最佳答案
您正在将规范化器
应用于文件对象。
我怀疑你真的想做这样的事情
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
关于python - 非英语字符的拼写纠正器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19601942/