【问题标题】:python text conversion into Pig Latinpython text conversion into Pig Latin
【发布时间】:2022-12-01 12:47:27
【问题描述】:

I need a python program for converting an input sentence into Pig Latin which has 2 rules:

  1. If a word begins with a consonant all consonants before the first vowel are moved to the end of the word and the letters "ay" are then added to the end. e.g. "coin" becomes "oincay" and "flute" becomes "uteflay".
  2. If a word begins with a vowel then "yay" is added to the end. e.g."egg" becomes "eggyay" and "oak" becomes "oakyay".

    I have written this program so far:

    string = input('String: ')
    
    if string[0].upper() in 'BCDFGJKLMNPQSTVXZHRWY':
    
        print(string.replace(string[0],'') + string[0]+'ay')
    
    if string[0].upper() in 'AEIOUY':
        print(string + 'yay')
    #vowels = [each for each in 
    

    but this only works for one word(whereas i need the whole sentence), and the first part only replaces the first consonant, not all (whereas I need to replace all consonants before the first vowel)

【问题讨论】:

    标签: python


    【解决方案1】:

    We can try using a regex replacement with a callback function:

    inp = "coin flute egg oak"
    output = re.sub(r'w+', lambda m: re.sub(r'(w)(w+)', r'ay', m.group()) if not re.search(r'^[AEIOUaeiou]', m.group()) else m.group() + 'yay', inp)
    print(output)  # oincay lutefay eggyay oakyay
    

    【讨论】:

      猜你喜欢
      • 2018-08-19
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多