验证英语文本中“a”和“an”的正确使用 - Python [关闭]

2024-03-28

我想创建一个程序,从文件中读取文本并指出“a”和“an”何时使用不正确。据我所知,一般规则是当下一个单词以元音开头时使用“an”。但还应该考虑到也应该从文件中读取例外情况。

有人可以给我一些关于如何开始使用这个的提示和技巧吗?功能或可能有帮助。

我会很高兴:-)

我对 Python 还很陌生。


这是一个解决方案,其中正确性定义为:an出现在以元音开头的单词之前,否则a可能用过了:

#!/usr/bin/env python
import itertools
import re
import sys

try:
    from future_builtins import map, zip
except ImportError: # Python 3 (or old Python versions)
    map, zip = map, zip
from operator import methodcaller

import nltk  # $ pip install nltk
from nltk.corpus import cmudict  # >>> nltk.download('cmudict')

def starts_with_vowel_sound(word, pronunciations=cmudict.dict()):
    for syllables in pronunciations.get(word, []):
        return syllables[0][-1].isdigit()  # use only the first one

def check_a_an_usage(words):
    # iterate over words pairwise (recipe from itertools)
    #note: ignore Unicode case-folding (`.casefold()`)
    a, b = itertools.tee(map(methodcaller('lower'), words)) 
    next(b, None)
    for a, w in zip(a, b):
        if (a == 'a' or a == 'an') and re.match('\w+$', w): 
            valid = (a == 'an') if starts_with_vowel_sound(w) else (a == 'a')
            yield valid, a, w

#note: you could use nltk to split text in paragraphs,sentences, words
pairs = ((a, w)
         for sentence in sys.stdin.readlines() if sentence.strip() 
         for valid, a, w in check_a_an_usage(nltk.wordpunct_tokenize(sentence))
         if not valid)

print("Invalid indefinite article usage:")
print('\n'.join(map(" ".join, pairs)))

输入示例(每行一个句子)



Validity is defined as `an` comes before a word that starts with a
vowel sound, otherwise `a` may be used.
Like "a house", but "an hour" or "a European" (from @Hyperboreus's comment http://stackoverflow.com/questions/20336524/gramatically-correct-an-english-text-python#comment30353583_20336524 ).
A AcRe, an AcRe, a rhYthM, an rhYthM, a yEarlY, an yEarlY (words from @tchrist's comment http://stackoverflow.com/questions/9505714/python-how-to-prepend-the-string-ub-to-every-pronounced-vowel-in-a-string#comment12037821_9505868 )
We have found a (obviously not optimal) solution." vs. "We have found an obvious solution (from @Hyperboreus answer)
Wait, I will give you an... -- he shouted, but dropped dead before he could utter the last word. (ditto)
  

Output

Invalid indefinite article usage:
a acre
an rhythm
an yearly

最后一对无效的原因并不明显,请参阅为什么是“一年一度”? https://english.stackexchange.com/q/46323/880

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

验证英语文本中“a”和“an”的正确使用 - Python [关闭] 的相关文章

随机推荐