【问题标题】:How to scramble the words in a sentence - Python如何打乱句子中的单词 - Python
【发布时间】:2014-04-05 08:18:10
【问题描述】:

我创建了以下代码来打乱单词中的字母(第一个和最后一个字母除外),但是如何打乱句子中单词的字母;给定输入要求一个句子而不是一个单词。感谢您的宝贵时间!

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

【问题讨论】:

标签: python sentence scramble


【解决方案1】:

我可以推荐random.shuffle()吗?

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

打乱词序:

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

打乱句子中的每个单词,保持顺序:

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

如果按原样保留第一个和最后一个字母很重要:

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

【讨论】:

  • 我也想到了第一件事,但 OP 的代码只交换单词中的两个随机字母,仅限于第一个或最后一个字母。假设这是所需的行为,shuffle 不适合该任务。
【解决方案2】:

使用split 方法将句子分成单词列表(和一些标点符号):

words = input().split()

然后做几乎与之前相同的事情,除了使用列表而不是字符串。

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

...

newWords = []

...

newWords.append(whatever)

不过,有比你现在做的更有效的方法来进行交换:

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

如果你真正想做的是将你的单词打乱应用到句子的每个单词上,你可以使用循环或列表理解来做到这一点:

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

如果您想完全随机化中间字母(或单词)的顺序,而不是仅仅交换两个随机字母(或单词),random.shuffle 函数可能会很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-18
    • 2014-05-16
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多