gpt4 book ai didi

python - 尝试制作一个根据用户输入用 "?"替换辅音单词的 Python 程序

转载 作者:行者123 更新时间:2023-12-01 00:31:01 26 4
gpt4 key购买 nike

这是我的情况;我正在尝试制作一个Python程序,它接受用户输入并检测任何辅音('B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T, V, X, Z') 在用户输入的字符串中,然后用“?”替换所述字母象征。并打印原始单词和找到的辅音的数量。

示例输出:

Please enter a word or zzz to quit: Dramatics
The original word is: dramatics
The word without consonants is: ??a?a?i??
The number of consonants in the word are: 6

我的代码:

 C =  input("Enter A Word (CAPITALS ONLY):")
S = str(C)
QUESTIONMARK = str("?")
chars = str('B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, X, Z')
if any((C in chars) for C in S):
FINAL = str.replace(QUESTIONMARK,str(S),chars)
print(FINAL)
else:
print('Not Found')

我的输出:

This is what is returned on WING Pro running Python 3.7:

 Enter A Word (CAPITALS ONLY):HELLO
?

If there are any solutions to this problem it would be greatly appreciated.

最佳答案

您可以使用以下内容来获取FINAL,这会将每个不是元音的元素替换为“?”:

FINAL = ''.join(e if e in "AEIOU" else "?" for e in S)

您可以对代码进行一些改进。如果您使用的是Python 3,input返回一个字符串,因此您不需要强制转换,您可以直接定义S,如下所示:

S = input("Enter A Word (CAPITALS ONLY):")
QUESTIONMARK = "?"
CONSONANTS = 'BCDFGHJKLMNPQRSTVXZ'

if any((C in CONSONANTS) for C in S):
FINAL = ''.join(e if e in "AEIOU" else "?" for e in S)
number_of_consonants = sum(1 for c in S if c in CONSONANTS)
print(FINAL)
else:
print('Not Found')

print(f'The original word is: {S}')
print(f'The word without consonants is: {FINAL}')
print(f'The number of consonants in the word are: {number_of_consonants}')

如果需要统计辅音的个数,可以使用下面的

CONSONANTS = 'BCDFGHJKLMNPQRSTVXZ'
number_of_consonants = sum(1 for c in S if c in CONSONANTS)

关于python - 尝试制作一个根据用户输入用 "?"替换辅音单词的 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58176700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com