除了第一个和最后一个字母之外,如何在python中对字符串的所有字母进行加扰/随机/随机化?

时间:2018-06-18 10:38:27

标签: string python-3.x shuffle

例如:

Example 1:
string = "Jack and the bean stalk."
updated_string = "Jcak and the baen saltk."
Example 2:
string = "Hey, Do you want to boogie? Yes, Please."
updated_string = "Hey, Do you wnat to bogoie? Yes, Palsee."

现在这个字符串存储在一个文件中。 我想从文件中读取这个字符串。并将更新的字符串写回文件中相同的位置。 长度大于3的字符串中每个单词的字母必须进行加扰/混洗,同时保持第一个和最后一个字母不变。此外,如果有标点符号,则标点符号保持不变。

我的方法:

import random
with open("path/textfile.txt","r+") as file:
    file.seek(0)
    my_list = []
    for line in file.readlines():
        word = line.split()
        my_list.append(word)

scrambled_list =[]
for i in my_list:
    if len(i) >3:
        print(i)
        s1 = i[1]
        s2 = i[-1]
        s3 = i[1:-1]
        random.shuffle(s3)
        y = ''.join(s3)
        z = s1+y+s2+' '
        print(z)

1 个答案:

答案 0 :(得分:0)

这是一种方法。

<强>演示:

from random import shuffle
import string

punctuation = tuple(string.punctuation)

for line in file.readlines():   #Iterate lines
    res = []
    for i in line.split():      #Split sentence to words
        punch = False
        if len(i) >= 4:         #Check if word is greater than 3 letters
            if i.endswith(punctuation):    #Check if words ends with punctuation 
                val = list(i[1:-2])        #Exclude last 2 chars
                punch = True
            else:
                val = list(i[1:-1])        #Exclude last 1 chars
            shuffle(val)               #Shuffle letters excluding the first and last.
            if punch:
                res.append("{0}{1}{2}".format(i[0], "".join(val), i[-2:]))
            else:
                res.append("{0}{1}{2}".format(i[0], "".join(val), i[-1]))
        else:
            res.append(i)
    print(" ".join(res))