【问题标题】:Python - scramble a sentencePython - 打乱一个句子
【发布时间】:2014-05-16 00:49:47
【问题描述】:

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

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

【问题讨论】:

  • 你到底卡在哪里了?打乱一个你不理解的单词会阻止你用它来打乱一个句子是什么意思?你尝试了什么?
  • 这看起来像是作业,但我无法抗拒:您可以将句子拆分为单个单词,然后将它们添加到集合中。一个集合的顺序是不确定的,所以你的句子会被打乱。
  • 我认为你的函数也可以使用列表,所以s=sentence.split() 然后' '.join(scramble(s))
  • 您可以使用random.shuffle(),只要记住使用您的数据副本,因为它会就地随机播放。

标签: python scramble


【解决方案1】:

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

word_list = sentence.split(" ")

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

scramble(word_list)

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

【讨论】:

  • 我添加了以下内容: def scrambleTwo(word): s = word while s == word: s = sentence.split(" ") (scramble(s)) return s
  • 单词分开,字母变了--如何打乱句子中单词的顺序?
【解决方案2】:

您的代码存在一些问题。一个是你可以打乱单个字母的单词,但你试试!您还需要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-05
    • 2014-03-31
    • 1970-01-01
    • 2019-03-25
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    相关资源
    最近更新 更多