-2

我正在尝试创建一个打乱单词和句子的程序。我有打乱单词的代码,但我不知道该怎么做才能打乱一个句子。有任何想法吗?提前致谢!!

import random

def main():
    word = input("Please enter a word or a sentence (if sentence, add a period to end the sentence: ")
    if "." in word:
        print(scramble(word))
    else:
        print(scrambleTwo(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

def scrambleTwo(word):


main()
4

2 回答 2

0

你需要split像这样在空格上写你的句子:

word_list = sentence.split(" ")

然后以与您打乱单词的方式类似的方式打乱结果数组。

scramble(word_list)

这需要是一个不同的加扰函数,专门用于加扰数组而不是字符串(但逻辑基本相同)。

于 2014-04-03T22:51:20.233 回答
0

您的代码有一些问题。一个是你可以打乱单个字母的单词,但你试试!您还想要raw_input而不仅仅是input. 最后,诀窍是用来split获取每个单词,然后您将其打乱。这是修改后的版本。

import random

def main():
    word = raw_input(
        "Please enter a word or a sentence "
        "(if sentence, add a period to end the sentence: ")
    if not "." in word:
        print(scramble(word))
    else:
        print(scrambleTwo(word))


def scramble(word):
    if len(word) < 2:
        return 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

def scrambleTwo(word):
    bits = word.split(" ")
    new_sentence_array = []
    for bit in bits:
        if not bit:
            continue
        new_sentence_array.append(scramble(bit))
    return " ".join(new_sentence_array)


main()
于 2014-04-03T23:07:13.993 回答