【发布时间】:2014-02-05 08:44:18
【问题描述】:
我正在尝试从网络论坛获取大量自然语言并使用 PyEnchant 更正拼写。文本通常是非正式的,并且是关于医疗问题的,因此我创建了一个文本文件“test.pwl”,其中包含相关的医疗词汇、聊天缩写等。在某些情况下,不幸的是,一小部分 html、url 等仍然保留在其中。
我的脚本旨在同时使用 en_US 字典和 PWL 来查找所有拼写错误的单词,并完全自动地将它们更正为 d.suggest 的第一个建议。它打印一个拼写错误的单词列表,然后是一个没有建议的单词列表,并将更正的文本写入“spellfixed.txt”:
import enchant
import codecs
def spellcheckfile(filepath):
d = enchant.DictWithPWL("en_US","test.pwl")
try:
f = codecs.open(filepath, "r", "utf-8")
except IOError:
print "Error reading the file, right filepath?"
return
textdata = f.read()
mispelled = []
words = textdata.split()
for word in words:
# if spell check failed and the word is also not in
# mis-spelled list already, then add the word
if d.check(word) == False and word not in mispelled:
mispelled.append(word)
print mispelled
for mspellword in mispelled:
#get suggestions
suggestions=d.suggest(mspellword)
#make sure we actually got some
if len(suggestions) > 0:
# pick the first one
picksuggestion=suggestions[0]
else: print mspellword
#replace every occurence of the bad word with the suggestion
#this is almost certainly a bad idea :)
textdata = textdata.replace(mspellword,picksuggestion)
try:
fo=open("spellfixed.txt","w")
except IOError:
print "Error writing spellfixed.txt to current directory. Who knows why."
return
fo.write(textdata.encode("UTF-8"))
fo.close()
return
问题在于输出通常包含对字典或 pwl 中单词的“更正”。例如,当输入的第一部分是:
我的新医生觉得我现在是双极的。这,在被其他人认为严重抑郁 9 年后
我知道了:
我的新医生觉得我现在是躁郁症。这是在被其他人认为严重抑郁 9 年后
我可以处理案件的变化,但医生 --> 医生一点也不好。当输入要短得多时(例如上面的引用是整个输入),结果是可取的:
我的新医生觉得我现在患有躁郁症。这,在被其他人认为严重抑郁 9 年后
谁能给我解释一下为什么?请用非常简单的话说,因为我对编程很陌生,对 Python 也很陌生。非常感谢您提供分步解决方案。
【问题讨论】:
标签: python dictionary spelling pyenchant enchant