1

我正在尝试在 python 中创建一个程序,该程序从用户那里获取一个句子并混淆所述单词的中间字母,但保持其他字母完整......现在我有代码可以重新排列所有用户输入的内容,只是忘记了空格...我会让我的代码为自己说话..它适用于单个单词输入,我想我会总结一下...我需要随机化用户输入的每个单词,然后保持其他单词完整..

import random


words = input("Enter a word or sentence") #Gets user input

words.split()

for i in list(words.split()): #Runs the code for how many words there are

    first_letter = words[0] #Takes the first letter out and defines it

    last_letter = words[-1] #Takes the last letter out and defines it

    letters = list(words[1:-1]) #Takes the rest and puts them into a list

    random.shuffle(letters) #shuffles the list above

    middle_letters = "".join(letters) #Joins the shuffled list

    final_word_uncombined = (first_letter, middle_letters, last_letter)                       #Puts final word all back  in place as a list

final_word = "".join(final_word_uncombined) #Puts the list back together again

print(final_word) #Prints out the final word all back together again
4

3 回答 3

2

您的代码几乎是正确的。修正后的版本是这样的:

import random

words = raw_input("Enter a word or sentence: ")
jumbled = []

for word in words.split(): #Runs the code for how many words there are
    if len(word) > 2:       # Only need to change long words
        first_letter = word[0] #Takes the first letter out and defines it
        last_letter = word[-1] #Takes the last letter out and defines it
        letters = list(word[1:-1]) #Takes the rest and puts them into a list
        random.shuffle(letters) #shuffles the list above
        middle_letters = "".join(letters) #Joins the shuffled list
        word = ''.join([first_letter, middle_letters, last_letter])

    jumbled.append(word)

jumbled_string = ' '.join(jumbled)
print jumbled_string
于 2012-10-24T16:06:51.677 回答
0

如果我正确理解了您的问题,那么您似乎走上了正轨,您只需为每个单词都扩展它

randomized_words = []
for word in words.split():
   #perform your word jumbling
   radomized_words.append(jumbled_word)

print ' '.join(randomized_words)

这会创建一个单独的混乱单词列表。用户单词输入中的每个单词都混杂在一起并添加到列表中以保持顺序。最后,打印出杂乱的单词列表。每个单词的顺序与用户输入的顺序相同,但字母混乱。

于 2012-10-24T15:54:04.673 回答
0

所以我读了这个问题,在公寓吃午饭的时候,我不得不涉水穿过交通。无论如何,这是我的单行贡献。说真的 alexeys 的答案是它在哪里。

sentence = input("Enter a word or sentence")
print " ".join([word[0] + ''.join(random.sample(list(word[1:-1]), len(list(word[1:-1])))) + word[-1] for word in sentence.split()])
于 2012-10-24T16:28:37.297 回答