题目:
学习语文时有中文重组句子,英语里也有重组句,定义一个函数 comb(sentence),其功能是把一英语句子的单词打乱,并把打乱的单词用一个空格连接起来,然后输出。如果句子的单词
小于等于 2 个就输出:原句的单词小于等于 2 个。(注意程序中的字符串全部使用双引号""表示)请把编号(1)~(7)和对应下划线删除,填空完成程序中的语句,不能修改已有的代码。
import random
def comb(sentence): #定义一个函数,参数为 sentence
words=(1)() #1 把单词分割出来
print("-"*60)
if len(words)==1 (2) len(words)==2: #2 如果句子中的单词小于 2 个,则不进行打乱,输出"
原句的单词小于等于 2 个"
print("原句的单词小于等于 2 个")
else:
jumble=[]
while (3): #3 对句子的单词进行打乱
site = (4)(len(words)) #4
jumble.(5)__ #5
words=_(6) #6 切片时位置如果是表达式要用括号()括起来
s=(7)(jumble) #7 把单词用一个空格连接起来
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)
import random
def comb(sentence): #定义一个函数,参数为 sentence
words=sentence.split() #1 把单词分割出来
print("-"*60)
if len(words)==1 or len(words)==2: #2 如果句子中的单词小于 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):] #6 切片时位置如果是表达式要用括号()括起来
s=' '.join(jumble) #7 把单词用一个空格连接起来
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)
import random
def comb(sentence): #定义一个函数,参数为 sentence
words=sentence.split()
print("-"*60)
if len(words)==1 or len(words)==2: #2 如果句子中的单词小于 2 个,则不进行打乱,输出"原句的单词小于等于 2 个"
print("原句的单词小于等于 2 个")
else:
jumble=[]
while len(words) != 0: #3 对句子的单词进行打乱
site = random.randrange(len(words)) #4
jumble.append(words[site])
words= words[0:site] + words[site+1:]#6 切片时位置如果是表达式要用括号()括起来
s=" ".join(jumble) #7 把单词用一个空格连接起来
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)
import random
def comb(sentence): #定义一个函数,参数为 sentence
words=sentence.split() #1 把单词分割出来
print("-"*60)
if len(words)==1 or len(words)==2: #2 如果句子中的单词小于 2 个,则不进行打乱,输出"原句的单词小于等于 2 个"
print("原句的单词小于等于 2 个")
else:
jumble=[]
while len(words)>0: #3 对句子的单词进行打乱
site = random.choice(range(len(words))) #4
jumble.append(words[site]) #5
words=words[:site]+words[site+1:] #6 切片时位置如果是表达式要用括号()括起来
s=' '.join(jumble) #7 把单词用一个空格连接起来
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)
测试结果:
原句为:
The Beijing Organising Committee for the 2022 Olympic and Paralympic Winter Games is a public institution with legal person status
------------------------------------------------------------句子打乱顺序后的单词组合为:
with status Beijing Winter is Paralympic The Games 2022 person public for Organising a institution Olympic the legal Committee and