【问题标题】:Pig latin string conversion in pythonpython中的Pig拉丁字符串转换
【发布时间】:2020-07-13 21:14:07
【问题描述】:

我正在尝试创建一个将文本转换为猪拉丁语的函数:简单的文本转换,它修改每个单词,将第一个字符移动到末尾并将“ay”附加到末尾。但我得到的只是一个空列表。有什么建议吗?

def pig_latin(text):
  say = ""
  words = text.split()
  for word in words:
    endString = str(word[1]).upper()+str(word[2:])
    them = endString, str(word[0:1]).lower(), 'ay'
    word = ''.join(them)
    return word

print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"

【问题讨论】:

  • 您要返回单词而不是单词吗?无论如何它可能会破裂
  • 为什么要拆分say而不是text
  • 我不确定我是否理解这个问题。如果我返回 word 我得到一个错误:第 13 行错误:print(pig_latin("hello how are you")) # 应该是 "ellohay owhay reaay ouyay" 第 11 行错误:返回 word UnboundLocalError: local variable 'word' referenced分配前
  • 在我看来,您可能在第三行拆分了错误的字符串。您不是打算将字符串变量“文本”拆分为“单词”,而不是空字符串“说”吗?
  • @emremrah 因为说是我要拆分的字符串不是吗?如果我拆分文本,我会得到:你很有趣

标签: python function for-loop


【解决方案1】:
def pig_latin(text):
  words = text.split()
  pigged_text = []

  for word in words:
    word = word[1:] + word[0] + 'ay'
    pigged_text.append(word)

  return ' '.join(pigged_text)

print(pig_latin("hello how are you"))

输出:ellohay owhay reaay ouyay

【讨论】:

  • 其实我的回答几乎和@ventaquil 一样,我没注意到。由于他/她首先回答,您可以选择他/她的答案作为接受的答案。
【解决方案2】:

我试过了,它对我有用


def pig_latin(text):
  say = []

  # Separate the text into words

  words = text.split()
  for word in words:

    # Create the pig latin word and add it to the list

    word = word[1:] + word[0] + "ay"
    say.append(word)

    # Turn the list back into a phrase

  return " ".join(say)

print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"

print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"


欢迎提出建议

【讨论】:

    【解决方案3】:
    def pig_latin(text):
      say = []
      # Separate the text into words
      words = text.split(" ")
      for word in words:
        # Create the pig latin word and add it to the list
        say.append(word[1:]+word[0]+'ay')
        # Turn the list back into a phrase
      return " ".join(x for x in say)
    

    【讨论】:

      【解决方案4】:

      为我工作

      def pig_latin(sentence):
          output = []
          for word in sentence.split(" "):
              word = word[1:] + word[0] + "ay"
              output.append(word)
          return " ".join(output)
      

      【讨论】:

        【解决方案5】:

        只需对每个单词使用列表理解,然后将它们重新组合在一起。

        编辑:此解决方案存在多个空格的问题,例如当人们在 colon: ! 之后放置两个空格时

        def dowork(sentence):
        
            def pigword(word):
                return "".join([word[1:], word[0], "ay"])
        
            return " ".join([pigword(word) for word in sentence.split()])
        
        
        dataexp = [
            ("hello how are you","ellohay owhay reaay ouyay"),
            ("programming in python is fun","rogrammingpay niay ythonpay siay unfay")
            ]
        
        for inp, exp in dataexp:
            got = dowork(inp)
            msg = "exp :%s:  for %s \n      got :%s:" % (exp, inp, got)
            if exp == got:
                print("good! %s" % msg)
            else:
                print("bad ! %s" % msg)
        

        输出

        good! exp :ellohay owhay reaay ouyay:  for hello how are you
              got :ellohay owhay reaay ouyay:
        good! exp :rogrammingpay niay ythonpay siay unfay:  for programming in python is fun
              got :rogrammingpay niay ythonpay siay unfay:
        

        【讨论】:

        • 为什么需要嵌套函数? ' '.join([x[1:]+x[0]+'ay' for x in 'hello world'.split()])
        • 好吧,它不必嵌套。但我喜欢把它变成自己的功能来分离关注点。各有各的。
        【解决方案6】:

        这是一个适用于我的解决方案:

           def pig_latin(text):
              # Separate the text into words
                words = text.split()
                #creating a new empty list called pig
                pig=[]
                # creating a for loop to alter every word in words
                for word in words:
                    
                    """here we are assigning the altered word to a new variable pigged_word. The we can remove first word alone from the original word usin
                        indexing and add/concat the letter at zeroth index (1st letter) back to the
                            word and add/concat new string 'ay' at end """
                    
                    pigged_word=word[1:]+word[0]+'ay'
                    #append the altered words to the list
                    # use append instead of insert since you can add word to end of list
                    pig.append(pigged_word)
                    #now convert it back to 
                return (' '.join(pig))
                    
            print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
            print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"
        

        请尝试理解问题并解决。拆分 say 变量是行不通的,理想情况下,您必须将文本拆分成几部分,即使那样您也不必与 " "

        拆分

        【讨论】:

          【解决方案7】:

          基于 Herman Singh 的回答,但省略了创建一个空列表并在 for 循环中附加到它的反模式(这样称呼它可能有点强)。

          def pig_latin(text):
              words = [
                  word[1:] + word[0] + "ay"
                  for word in text.split()
              ]
              return " ".join(words)
          
          
          print(pig_latin("hello how are you"))  # Should be "ellohay owhay reaay ouyay"
          print(pig_latin("programming in python is fun"))  # Should be "rogrammingpay n
          

          这可以简化为一行,但我认为它不利于可读性。

          def pig_latin(text):
              return " ".join([word[1:] + word[0] + "ay" for word in text.split()])
          
          
          print(pig_latin("hello how are you"))  # Should be "ellohay owhay reaay ouyay"
          print(pig_latin("programming in python is fun"))  # Should be "rogrammingpay siay unfay
          

          【讨论】:

            【解决方案8】:
            def pig_latin(text):
              # Separate the text into words
              words = text.split()
              newWord = []
              for word in words:
                # Create the pig latin word and add it to the list
                n = ""
                for char in range(len(word)-1, -1, -1):
                  if(char == 0) :
                    n+= (word[char]+"ay")
                  n += word[char]
                newWord.append(n)    
                # Turn the list back into a phrase
              return " ".join(newWord)
                
            print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
            print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"
            

            【讨论】:

              【解决方案9】:
              def pig_latin(text):
                say = ""
                words = text.split()
                for word in words:
                  word=word[1:] + word[0] + "ay" + " "
                  say +=word
                return say
                      
              print(pig_latin("hello how are you"))
              

              【讨论】:

              • 欢迎来到 StackOverflow!虽然此答案可能会解决 OP 的问题,但建议提供有关书面代码的解释,以使您的答案更容易被社区理解并提高其质量
              【解决方案10】:

              只需使用列表推导即可实现紧凑性和简单性:

              ’ ‘.join([word[1:] + word[0] + ‘ay’ for word in text.split(‘ ‘)])

              【讨论】:

                【解决方案11】:

                def pig_latin(文本):

                say = ""
                  pig_list= []
                  # Separate the text into words
                  words = text.split(' ')
                  for word in words:
                    # Create the pig latin word and add it to the list
                    word = word[1:] + word[0] + "ay"
                    # print(word)
                    pig_list.append(word)
                    # Turn the list back into a phrase
                    say = ' '.join(pig_list)
                  return say
                

                【讨论】:

                  【解决方案12】:

                  没有.join.append的解决方案:

                  def pig_latin(text):
                    say = ""
                    words = text.split()
                    for word in words:
                      pig_word = word[1:] + word[0] + "ay "
                      say += pig_word
                    return say
                          
                  print(pig_latin("hello how are you")) # "ellohay owhay reaay ouyay"
                  print(pig_latin("programming in python is fun")) # "rogrammingpay niay ythonpay siay unfay"
                  

                  【讨论】:

                    【解决方案13】:
                    def pig_latin(text):
                      say = ""
                      # Separate the text into words
                      words = text.split()
                      for word in words:
                        # Create the pig latin word and add it to the list
                        say += word[1:] + word[0] + "ay "
                        # Turn the list back into a phrase
                      return say.rstrip(" ")
                    
                    print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
                    print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"
                    

                    【讨论】:

                      【解决方案14】:
                      def pig_latin(text):
                          say = ""
                          str=[]
                        # Separate the text into words
                          words = text.split()
                         for word in words:
                           # Create the pig latin word and add it to the list
                            say=word[1:]+word[:1]+"ay"
                            str.append(say)
                            # Turn the list back into a phrase
                            joined=" ".join(str)
                            return joined
                          
                      print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
                      print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay 
                      ythonpay siay unfay"
                      

                      【讨论】:

                        【解决方案15】:
                        def pig_latin(text):
                          say = ""
                          # Separate the text into words
                          words = text.split()
                          for word in words:
                            # Create the pig latin word and add it to the list
                            say = say + word[1:] +word[0] +"ay "
                            # Turn the list back into a phrase
                          return "".join(say)
                        
                        print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
                        print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"
                        

                        【讨论】:

                          【解决方案16】:
                          def pig_latin(text):
                            say = " "
                            # Separate the text into words
                            words = text.split()
                            for word in words:
                              # Create the pig latin word and add it to the   list
                              say+=word[1:]+word[0]+str("ay")+ " "
                              # Turn the list back into a phrase
                            return say
                              
                          print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
                          print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"
                          

                          【讨论】:

                            【解决方案17】:
                            def pig_latin(text):
                              say = ""
                              # Separate the text into words
                              words = text.split()
                              for word in words:
                                # Create the pig latin word and add it to the list
                                say += " {}{}ay".format(word[1:], word[0])
                                # Turn the list back into a phrase
                              return say
                                
                            print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
                            print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"
                            

                            【讨论】:

                              【解决方案18】:

                              使用以下代码:

                              def pig_latin(texts):
                                  return ' '.join([text.replace(text[0],'') + text[0]+'ay' for text in texts.split()])
                              
                              print(pig_latin("hello how are you"))
                              print(pig_latin("programming in python is fun"))
                              

                              会得到想要的结果:

                              ellohay owhay reaay ouyay
                              rogrammingpay niay ythonpay siay unfay
                              

                              【讨论】:

                                猜你喜欢
                                • 1970-01-01
                                • 1970-01-01
                                • 2016-08-05
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                相关资源
                                最近更新 更多