在句子中正确使用a或an

2024-04-28 12:15:29 发布

您现在位置:Python中文网/ 问答频道 /正文

想象一下一个骰子滚筒,你想打印出语法良好的结果。你知道吗

  • 'You rolled a 18'是语法错误的一个例子。你知道吗
  • 'You rolled an 18'是良好语法的一个例子。你知道吗
  • 'You rolled an 5'语法不好。你知道吗

我可以定义一个函数来执行一堆if语句,但这看起来不像是Pythonic。你知道吗

#ideally something like this 
print(f'You rolled {a-or-an} {someint}')

Tags: 函数youanif定义语法语句骰子
3条回答

如果使用num2word(由pip install num2word安装)

import num2word
a-or-an ='an' if numtoword.to_card(someint)[0] == 'e' else 'a'

不幸的是,因为它是基于声音的,而声音是基于单词的,我不认为有一种方法可以通过检查整数来做到这一点,因此解决方案不是很pythonic。你知道吗

也可以随意反驳(我不知道)

前面的问题在下面的评论中被11推翻了,现在应该解决了。你知道吗

这是我未优化的想法。把其他答案改成英语,然后根据第一个字母(如果是元音)改冠词(a/an)。除了one中的o之外,因为one这个词实际上听起来像won,其中有一个辅音w作为第一个音。你知道吗

不管怎样,这是我的主意。你知道吗

from random import randint

import inflect # python -m pip install inflect

p = inflect.engine()

numlist = [1,7,8,10,11,12,11000000]

#for i in range(0, 10):
for i in numlist:
    article = 'a'
    num = i #randint(0, 10000000000)
    numword = p.number_to_words(num)
    if numword[:1] in 'aeiu':
        article = 'an'

    print("You rolled ", article, " ", num, " (", numword, ")", sep='')

基于comments中的discussion,我认为以下内容对您有用:

def getDiceRollString(someint):
    a_or_an = "an" if someint in (11, 18) or str(someint)[0] == '8' else "a"
    return "You rolled %s %d" % (a_or_an, someint)

你可以试试:

for i in [1, 5, 8, 11, 15, 18, 28, 81, 88, 800]:
    print(getDiceRollString(i))
#You rolled a 1
#You rolled a 5
#You rolled an 8
#You rolled an 11
#You rolled a 15
#You rolled an 18
#You rolled a 28
#You rolled an 81
#You rolled an 88
#You rolled an 800

相关问题 更多 >