[英]How to scramble the words in a sentence - 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()
拆分句子译成的话(和一些标点符号)的列表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
函数可能很有用。
我可以建议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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.