python - 非英语字符的拼写纠正器

标签 python regex python-3.x spelling

已阅读 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/

相关文章:

python - numpy 用整数递增地替换元素组

python - CPython 是否实现了 PEP 380 中提到的优化?

mysql - 优化在 JOIN 中使用 REGEXP 的 SQL 查询

python - 匹配所有不以 ':' Python 正则表达式开头的单词

python - 正则表达式匹配 Django 项目中 URL 模式中使用的字母和数字的组合?

python - 如何分离数组并根据数组中的索引添加它们?

python - 从上一级目录导入文件

python - 了解类变量的引用计数

python - 在 Python 中使用组合数学列出 4 位密码

list - 如果匹配字符串,则查找和删除列表元素