访问拆分列表中的某些单词

时间:2012-10-24 15:42:33

标签: python list random split shuffle

我正在尝试在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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如果我正确地理解了你的问题,看起来你正在走上正轨,你只需要为每个单词扩展这个

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

print ' '.join(randomized_words)

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

答案 2 :(得分: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()])