我试图得到一篇文章中拼写正确/拼写错误与整个文章的比率。我有一个计算拼写错误数量的方法,但它似乎有些臃肿。在for循环中,有没有更具python风格的方法来增加我的good
/bad
计数器?你知道吗
import enchant
from enchant.tokenize import get_tokenizer, HTMLChunker, EmailFilter, URLFilter
d = enchant.Dict("en_US")
good = 0
bad = 0
text = "this is <span class='stupid'>not important</span>. Email you@example.com from http://www.google.com. htis si a msispelling"
tokenizer = get_tokenizer("en_US", (HTMLChunker,),(URLFilter,EmailFilter))
# This loop here: Can I make this more efficient?
for (word,pos) in tokenizer(text):
if d.check(word):
good += 1
else:
bad += 1
print good # Prints 7
print bad # Prints 3
你可以这样做
例如,Python将
False
解释为0
,将True
解释为1
,这是利用了这一事实因此在上面的代码中,对列表理解的结果求和将是对
True
和False
值的列表求和,这实际上与只对True
值求和是一样的。你知道吗那么
bad
数就是总数减去good
。你知道吗因为
good
和bad
有些关联,所以用字典代替。你知道吗就执行时间而言,这可能没有显著提高效率。你知道吗
“Pythonic”通常是指最直截了当或最容易阅读的,所以我不这么认为。但这利用了一些可能更快的技巧。你知道吗
相关问题 更多 >
编程相关推荐