Python 题,有教一下的吗

英语有连词造句,现要求英语句子打乱成词。定义一个函数comb(sentence),其功能是把一英语句子的单词打乱,并把打乱的单词用一个空格连接起来,然后输出。如果句子的单词小于等于2个就输出:原句的单词小于等于 2 个。

(注意程序中的字符串全部使用双引号""表示)
请把编号(1)~(7)和对应下划线删除,填空完成程序中的语句,不能修改已有的代码。

import random 
def comb(sentence):  
          words=___(1)____() #1  
          print("-"*60) 
          if len(words)==1 ____(2)____ len(words)==2: #2  
                  print("原句的单词小于等于 2 个") 
          else: 
                  jumble=[] 
                  while ___(3)___: #3  
                            site = ____(4)___(len(words)) #4 
                             jumble.____(5)____ #5 
                            words= words[:site]+words[(site+1):]  
                  s=____(6)____(jumble) #6  
                  print("句子打乱顺序后的单词组合为:\n",s) 
if __name__=="__main__": 
           txt="The Beijing Organising Committee for the 2022 Olympic and Paralympic Winter Games is a public institution with legal person status" 
           print("原句为:\n", ____(7)____) 
           comb(txt) 

填空结果如下,望采纳下:


import random 
def comb(sentence):  
          words= sentence.split() #1
          print("-"*60) 
          if len(words)==1 or len(words)==2: #2
                  print("原句的单词小于等于 2 个") 
          else: 
                  jumble=[] 
                  while words: #3
                        site = random.randrange(len(words)) #4
                        jumble.append(words[site]) #5
                        words= words[:site]+words[(site+1):]
                  s=' '.join(jumble) #6
                  print("句子打乱顺序后的单词组合为:\n",s)

if __name__=="__main__": 
           txt="The Beijing Organising Committee for the 2022 Olympic and Paralympic Winter Games is a public institution with legal person status" 
           print("原句为:\n",txt)
           comb(txt) 
  • 以下回答由chatgpt基于相关博客总结生成:

    问题1:

    def mix_words(sentence): # 筛选出句子中的单词 words = sentence.split() # 如果单词小于等于2个,则输出原句 if len(words) <= 2: return sentence # 打乱单词的顺序 random.shuffle(words) # 用空格连接单词 mixed_sentence = " ".join(words) # 返回打乱顺序的句子 return mixed_sentence

    测试

    print(mix_words('This is a test sentence.'))

    This sentence is a test.

    print(mix_words('Hello, world!'))

    Hello, world!

    print(mix_words('Python is awesome.'))

    awesome. is Python