【问题标题】:How can I capture characters in a string up to the first vowel and create substring out of it?如何捕获字符串中直到第一个元音的字符并从中创建子字符串?
【发布时间】:2016-04-05 16:26:15
【问题描述】:

目前,我的代码的第一部分工作正常。如果它检测到第一个字符(索引 0)是元音,它会停止并在单词末尾添加“yay”。

第二部分旨在捕捉到第一个元音的辅音。这可以正常工作。

当我尝试获取原始单词并将所有内容切掉到第一个元音并从中创建一个新的子字符串时,就会出现问题。这意味着如果用户输入“hello”,它应该输出“ellohay”。我可以得到“hellohay”,但不知道如何捕捉这些初始辅音并将它们切掉。

# Pig Latinify

vowels = ['a', 'e', 'i', 'o', 'u']
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z']


def pig_latinify():
    state = True
    while state == True:

        user_input = raw_input("Enter a word to be translated: ").lower()

        # If the first character in input is a vowel add 'yay' to input and print.
        if user_input[0] in vowels[0:]:
            print ""
            print "Begins with a vowel." 
            pig_output = user_input + "yay"
            print user_input, "becomes:", pig_output
            print ""
        else:
            print ""
            print "Doesn't begin with a vowel."

            captured_consonants = ""
            captured_substring = ""
            new_user_input = ""

            # Capture the consonants up to the first vowel
            for i in user_input:
                if i in vowels:
                    break
                if i in consonants:
                    captured_consonants = captured_consonants + i

            # Slice user_input up to the first vowel and create a substring beginng from the first vowel until the end of the string.
                if i in consonants:
                    break
                if i in vowels:
                    captured_substring = captured_substring + i 
                print captured_substring

            # Concatenate substring of user_input with captured_consonants and 'ay'
            pig_output = captured_substring + captured_consonants + "ay"
            print user_input, "becomes:", pig_output
            print ""

pig_latinify()

【问题讨论】:

    标签: python python-2.7 slice


    【解决方案1】:

    如果你想删除所有前导字符直到你碰到一个元音,你可以使用itertools.dropwhile

    from itertools import dropwhile
    user_input = "hello"
    
    vowels = {"a","e","i","o","u"}
    
    up_to = "".join(dropwhile(lambda x: x not in vowels, user_input))
    print(up_to + user_input[:len(user_input) - len(up_to)]+"ay")
    

    输出:你好

    lambda x: x not in vowels 表示我们要删除所有字符,直到在元音中找到一个字符。如果您想使用大写或小写,请将大写元音添加到集合中或将 lambda 切换为 x.lower() not in vowels

    【讨论】:

    • 或者只是将 lambda 更改为 x.lower()
    • @JonClements,没错,OP 实际上是在输入字符串上调用 lower,所以可能是一个没有实际意义的问题,但我还是会添加它
    • ...和set('aeiou') 打字少了一点:)
    • 我不认为这正是猪拉丁 OP 正在寻找的。他想要“ellohay”而不是“elloyay”。但我喜欢你的解决方案多么简洁!
    • @VaibhavAggarwal,确实,不知道我在哪里看到另一个y,甚至还没喝过酒……
    【解决方案2】:

    这段代码看起来很奇怪。例如,第二个if i in vowels: 永远不会到达。

    您可能想要:

    1. 找到第一个元音的位置 - 让它成为pos
    2. 检查pos是否>0
    3. return user_input[pos:] + user_input[:pos-1] + 'ay'

    【讨论】:

      【解决方案3】:

      使用正则表达式可能是你最好的选择:

      # Pig Latinify
      import re
      
      vowels = list('aeiou')
      
      def pig_latinify():
          state = True
          while state == True:
      
              user_input = raw_input("Enter a word to be translated: ").lower()
      
              # If the first character in input is a vowel add 'yay' to input and print.
              if user_input[0] in vowels[0:]:
                  print ""
                  print "Begins with a vowel." 
                  pig_output = user_input + "yay"
                  print user_input, "becomes:", pig_output
                  print ""
              else:
                  print ""
                  print "Doesn't begin with a vowel."
      
                  r = re.search("(.*?)([aeiou].*)", user_input)
      
                  # Capture the consonants up to the first vowel
                  captured_consonants = r.groups()[0]
      
                  # Slice user_input up to the first vowel and create a substring beginng from the first vowel until the end of the string.
                  captured_substring = r.groups()[1]
      
                  # Concatenate substring of user_input with captured_consonants and 'ay'
                  pig_output = captured_substring + captured_consonants + "ay"
                  print user_input, "becomes:", pig_output
                  print ""
      
      pig_latinify()
      

      这基本上是非贪婪地搜索字符串,直到它碰到一个元音,并制作两组辅音和元音+跟随的字符串,并相应地操作它们。

      $ python pig_latin.py 
      Enter a word to be translated: hello
      
      Doesn't begin with a vowel.
      hello becomes: ellohay
      
      Enter a word to be translated: hi
      
      Doesn't begin with a vowel.
      hi becomes: ihay
      
      Enter a word to be translated: apple
      
      Begins with a vowel.
      apple becomes: appleyay
      

      【讨论】:

      • 当您说“非贪婪”时,这是否意味着不使用循环并迭代每个索引值?而是将其作为“搜索”吗?
      • @lookininward 非贪婪意味着它一直到输入中的第一个元音,并将其分组。如果它是贪婪的,它会一直持续到输入中的最后一个元音。
      • @lookininward docs.python.org/2/howto/regex.html#repeating-things 以获得更深入的解释。
      • @lookininward 请将答案标记为正确,如果这里的任何人帮助解决了您的问题。
      猜你喜欢
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多