How to scramble the words in a sentence - Python

橙三吉。 提交于 2021-02-11 18:19:57

问题


I have created the following code to scramble the letters in a word (except for the first and last letters), but how would one scramble the letters of the words in a sentence; given the input asks for a sentence instead of a word. Thank you for your time!

import random

def main():
    word = input("Please enter a word: ")
        print(scramble(word)) 

def scramble(word):
    char1 = random.randint(1, len(word)-2)
    char2 = random.randint(1, len(word)-2)
    while char1 == char2:
        char2 = random.randint(1, len(word)-2)
    newWord = ""

    for i in range(len(word)):
        if i == char1:
            newWord = newWord + word[char2]
        elif i == char2:
        newWord = newWord + word[char1]

        else:

            newWord = newWord + word[i]

    return newWord

main()

回答1:


May I suggest random.shuffle()?

def scramble(word):
    foo = list(word)
    random.shuffle(foo)
    return ''.join(foo)

To scramble the order of words:

words = input.split()
random.shuffle(words)
new_sentence = ' '.join(words)

To scramble each word in a sentence, preserving the order:

new_sentence = ' '.join(scramble(word) for word in input.split())

If it's important to preserve the first and last letters as-is:

def scramble(word):
    foo = list(word[1:-1])
    random.shuffle(foo)
    return word[0] + ''.join(foo) + word[-1]



回答2:


Split the sentence into a list of words (and some punctuation) with the split method:

words = input().split()

and then do pretty much the same thing you were doing before, except with a list instead of a string.

word1 = random.randint(1, len(words)-2)

...

newWords = []

...

newWords.append(whatever)

There are more efficient ways to do the swap than what you're doing, though:

def swap_random_middle_words(sentence):
    newsentence = list(sentence)

    i, j = random.sample(xrange(1, len(sentence) - 1), 2)

    newsentence[i], newsentence[j] = newsentence[j], newsentence[i]

    return newsentence

If what you actually want to do is apply your one-word scramble to each word of a sentence, you can do that with a loop or list comprehension:

sentence = input().split()
scrambled_sentence = [scramble(word) for word in sentence]

If you want to completely randomize the order of the middle letters (or words), rather than just swapping two random letters (or words), the random.shuffle function is likely to be useful.



来源:https://stackoverflow.com/questions/22161075/how-to-scramble-the-words-in-a-sentence-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!