Python - 争抢一个句子

时间:2014-04-03 22:47:17

标签: python scramble

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

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()

2 个答案:

答案 0 :(得分:0)

你需要split你的句子如下:

word_list = sentence.split(" ")

然后以类似的方式对结果数组进行加扰。

scramble(word_list)

这需要是一个不同的加扰函数,它们被定制为加扰数组而不是字符串(但逻辑基本上是相同的。)

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