这个程序在一个句子中加上单词并加扰它们。 规则是: - 第一个和最后一个字母保持不变 - 单词末尾的标点符号保持不变 - 带有单词的标点符号像中间字母一样乱码
我的问题是,如果我在一个单词的末尾有多个标点符号,它就不会加扰它。
Ex)测试!!!应该像t!ste!nig!或者t!est!nig! 但不是tstenig !!!
我该如何解决?
import random
import string
original_text = input("Enter your text: ").split(' ')
seed = int(input("Enter a seed (0 for random): "))
punctuation = []
for c in string.punctuation:
punctuation.append(c)
if seed is not 0:
random.seed(seed)
randomized_list = []
def scramble_word(word):
alpha = word[0]
end_punctuation = ''
if word[-1] in punctuation:
x = -1
while word[x] in punctuation:
end_punctuation += word[x]
x -= 1
omega = word[x]
middle = word[1: x]
else:
omega = word[-1]
middle = word[1:-1]
end_punctuation = ""
middle_list = list(middle)
random.shuffle(middle_list)
shuffled_text = "".join(middle_list)
new_words = alpha + shuffled_text + omega + end_punctuation
return new_words
for item in original_text:
if len(item) <= 3:
randomized_list.append(item)
else:
randomized_list.append(scramble_word(item))
new_words = " ".join(randomized_list)
print(new_words)
答案 0 :(得分:1)
问题是你没有在标点符号中加入随机播放;见下面两条修改的行:
if word[-1] in punctuation:
x = -1
while word[x] in punctuation:
end_punctuation += word[x]
x -= 1
omega = word[x]
middle = word[1: x] + end_punctuation[1:] # Include all except the final character
end_punctuation = end_punctuation[0] # Just use the final character
else:
omega = word[-1]
middle = word[1:-1]
end_punctuation = ""
这对我有用:
In [63]: scramble_word('hello!?$')
Out[63]: 'hle?l!o$'
In [64]: scramble_word('hello!?$')
Out[64]: 'h?!ello$'
In [65]: scramble_word('hello!?$')
Out[65]: 'hlel!?o$'
In [66]: scramble_word('hello!')
Out[66]: 'hlleo!'
In [67]: scramble_word('hello!')
Out[67]: 'hello!'
In [68]: scramble_word('hello!')
Out[68]: 'hlleo!'
In [69]: scramble_word('hello')
Out[69]: 'hlelo'
顺便说一下,你不需要punctuation
变量; word[x] in string.punctuation
也会一样。
答案 1 :(得分:1)
我对它的看法,可以缩短代码。 (在Python 3.5.1中)
import random
words = input("Enter your text: ")
def scramble(words):
for x in words.split():
middle = x[1:-1]
middle_list = list(middle)
random.shuffle(middle_list)
shuffled = "".join(middle_list)
print ("".join(x[0]+shuffled+x[-1]),"", end="")
scramble(words)
我的输出来自:
马斯特森!!%安培;烘烤%$土豆很棒!
要 !包换OSRS一%放大器; mkeas bigkna%$ patooets gerat!
我确信有人可以更加戏剧性地缩短它。