【问题标题】:How to get vowels, consonants and other characters from a text如何从文本中获取元音、辅音和其他字符
【发布时间】:2016-11-08 20:44:31
【问题描述】:

我需要一个程序,要求用户输入任何文本,然后显示三个字符串,第一个由文本中的所有元音组成,第二个由所有辅音组成,第三个由所有其他字符组成。我现在在一个while循环中,我想知道如何将它转移到Python中的for循环中。

text = input("Enter text: ")

# Loop counter
i = 0

# Accumulators
vows_string = ""
cons_string = ""
other_str = ""

while i < len(text):
    char = text[i]
    if char in "aioueAIOUE":
        vows_string += char
    elif char.isalpha():
        cons_string += char
    else:
        other_str += char
    i += 1

# Add pseudo-guillemets to make spaces "visible"
print(">>" + vows_string + "<<")
print(">>" + cons_string + "<<")
print(">>" + other_str + "<<")

【问题讨论】:

    标签: python parsing for-loop while-loop


    【解决方案1】:

    由于字符串是可迭代的,所以可以替换

    while i < len(text):
        char = text[i]
    

    for char in text:
        # no more need for 'i'
    

    顺便试试if char.lower() in "aioue":

    【讨论】:

    • 啊,迟到了 17 秒,不得不重新阅读问题以弄清楚需要什么。
    • 谢谢,它成功了,让我的代码更简单了
    【解决方案2】:

    现在代码很简单,让我们通过为元音使用set() 而不是字符串来提高效率:

    # Vowels Set
    vowels = set("aeiouAEIOU")
    
    # Accumulators
    vowels_string = ""
    consonants_string = ""
    other_string = ""
    
    # User Input
    text = input("Enter text: ")
    
    # Process Text
    for char in text:
        if char.isalpha():
            if char in vowels:
                vowels_string += char
            else:
                consonants_string += char
        else:
            other_string += char
    
    # Add pseudo-guillemets to make spaces "visible"
    print("<<", vowels_string, ">>", sep="")
    print("<<", consonants_string, ">>", sep="")
    print("<<", other_string, ">>", sep="")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 2017-10-21
      相关资源
      最近更新 更多