试图制作一个用“?”代替辅音词的Python程序基于关闭的用户输入

时间:2019-10-01 00:28:20

标签: python

这是我的情况;我正在尝试制作一个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')

我的输出:

  

这是在运行Python 3.7的WING Pro上返回的内容:

 Enter A Word (CAPITALS ONLY):HELLO
 ?
     

如果有解决此问题的方法,将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以使用以下命令获取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)

答案 1 :(得分:1)

您可以通过列表理解来做到这一点:

vowels='aeiou'
word = input('Please enter a word or zzz to quit: ')
print('The original word is: '+word.lower())
masked = ''.join([l if l.lower() in vowels else '?' for l in word])
print('The word without consonants is: '+masked)
print('The number of consonants in the word are: '+str(masked.count('?')))

输出:

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