有没有办法让这段代码更长,但做同样的事情?

时间:2016-06-25 14:55:17

标签: python loops counting

sentence = input("What is your sentence?")
sentence=sentence.capitalize()
counta = sentence.count("a")
counte = sentence.count("e")
counti = sentence.count("i")
counto= sentence.count ("o")
countu= sentence.count ("u")
countA2 = sentence.count("A")
countE2 = sentence.count("E")
countI2 = sentence.count("I")
countO2 = sentence.count("O")
countU2 = sentence.count("U")
countI3 = sentence.count(" I ")
countspaces = sentence.count(" ")
a1 = sentence.count("!")
a2 = sentence.count(".")
a3 = sentence.count(">")
a4 = sentence.count("<")
a5 = sentence.count(":")
a6= sentence.count(";")
a7 = sentence.count("'")
a8 = sentence.count("@")
a9 = sentence.count("#")
a10 = sentence.count("~")
a11= sentence.count("{")
a12= sentence.count("}")
a13= sentence.count("[")
a14 = sentence.count("]")
a15 = sentence.count("-")
a16 = sentence.count("_")
a17 = sentence.count("+")
a18 = sentence.count("=")
a19 = sentence.count("£")
a20 = sentence.count("$")
a21= sentence.count("%")
a22 = sentence.count("^")
a23= sentence.count("&")
a24 = sentence.count("(")
a25= sentence.count(")")
a26=sentence.count("?")
count = (counta + counte + counti + counto + countu + countA2 + countE2 +     countI2 + countO2 + countU2 + countI3)
speci= a1+a2+a3+a4+a5+a6+a7+a8+a9+a10+a11+a12+a13+a14+a15+a16+a17+a18+a19+a20+a21+a22+a23+a24+a25+a26)
print(sentence)
print("This has", speci, "special characters")
print("This has", countspaces, "Spaces")
print("This has", count, "vowels")

您可以看到上面的代码是waaayyy太久了。我不知道如何做同样的事情(这是用户输入句子,它计算元音,空格和特殊字符),但代码较少。如果你知道更好的方法。请告诉我。因为当然编码是关于最好的代码,这看起来很奇怪,是最好的方式。 谢谢你的帮助

4 个答案:

答案 0 :(得分:2)

如果要检查特殊字符,请执行以下操作:

special_char = 0
for i in sentence:
    if i.isalpha() == False and i.isdigit() == False:
        special_char += 1

对于空格:

spaces = sentence.count(' ')

对于元音,请创建一个以元音为键的字典,然后浏览整个输入并与元音字典中的各个键进行匹配。

答案 1 :(得分:0)

一个循环来统治所有人:

sentence = raw_input()
vowels = special_char = spaces = 0
for letter in sentence.lower():
    if letter in ['a', 'e', 'i', 'o', 'u']:
        vowels += 1
    elif letter == ' ':
        spaces += 1
    elif not (letter.isalpha() or letter.isdigit()):
        special_char += 1
print("Vowels: {},Spaces: {},Special Chars: {}".format(vowels,spaces,special_char))

答案 2 :(得分:0)

看看解决方案,你可能已经下定决心了。只需通过选择您要使用的单个字符来缩短它,请尝试以下代码。

word = "banana"
characters = ["A", "E", "I", "O", "U"]
for letter in word:
    if letter in characters:
        print("Special character.")

当然,使用与我添加元音相同的方式在列表中添加更多字符。

答案 3 :(得分:0)

如果你喜欢列表理解:


EXCEPTION: Cannot find a differ supporting object 'List []' of type 'object'. NgFor only supports binding to Iterables such as Arrays.