如何拼凑句子中的单词-Python

2024-05-18 17:43:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了下面的代码来拼凑单词中的字母(除了第一个和最后一个字母),但是如果输入的是一个句子而不是一个单词,那么如何拼凑一个句子中单词的字母呢。谢谢你抽出时间!

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

Tags: 代码lenmaindef字母时间random单词
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()吗?

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]

相关问题 更多 >

    热门问题