gpt4 book ai didi

Python 扰码器程序

转载 作者:行者123 更新时间:2023-12-01 03:38:02 29 4
gpt4 key购买 nike

该程序将句子中的单词打乱。规则是:- 第一个和最后一个字母保持不变- 单词末尾的标点符号保持不变- 单词中的标点符号像中间字母一样被打乱

我的问题是,如果我在单词末尾有多个标点符号,它不会打乱它。

例如)测试!!!应该是类似 t!ste!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)

最佳答案

问题是你没有在随机播放中添加标点符号;请参阅下面修改后的两行:

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 变量; string.punctuation 中的 word[x] 的工作原理相同。

关于Python 扰码器程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40099459/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com