如果不是某个单词,则将随机字符放入字符串中

2024-07-04 08:11:16 发布

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

例如,我有以下字符串:

Hello how are you today, [name]?

我该如何在随机选择的单词之间随机地放置字符,而不是[name]?我已经有了下面这段代码,但我希望有更好的方法来实现它。在

^{pr2}$

虽然这会用另一个随机字符替换这个字符。我该用什么方法让它随机替换或者在一个字符之后或之前放置一个随机字符?在

基本上我只是想模拟一种打字错误生成器。在

谢谢

到目前为止我的代码更新:

string = 'Hey how are you doing, [name]?'
characters = 'aeiou'
arr = string.rsplit(" ")
for i in range(0, len(arr)):
    x = arr[i]
    if x == '[name]': continue
    if len(x) > 3:
        if random.random() > 0.7:
            rnd = random.randint(0,len(x)-1)
            rndCharacter = random.choice(characters)
            if random.random() > 0.7:
                x = x[0:rnd] + rndCharacter + x[rnd+1:]
            else:
                x = x[:rnd] + rndCharacter + x[rnd:]
            arr[i] = x
    else:
        if random.random() > 0.7:
            rnd = random.randint(0,len(x)-1)
            rndCharacter = random.choice(characters)
            x = x[:rnd] + rndCharacter + x[rnd:]
            arr[i] = x
print " ".join(arr)

> Hey houw are you doiang, [name]?

更新:

也许我对代码的最后更新,希望这能在将来帮助别人解决一些问题

def misspeller(word):
    typos = { 'a': 'aqwedcxzs',
              'b': 'bgfv nh',
              'c': 'cdx vf',
              'd': 'desxcfr',
              'e': 'e3wsdfr4',
              'f': 'fredcvgt',
              'g': 'gtrfvbhyt',
              'h': 'hytgbnju',
              'i': 'i8ujko9',
              'j': 'juyhnmki',
              'k': 'kiujm,lo',
              'l': 'loik,.;p',
              'm': 'mkjn ,',
              'n': 'nhb mjh',
              'o': 'o9ikl;p0',
              'p': 'p0ol;[-',
              'q': 'q1asw2',
              'r': 'r4edft5',
              's': 'swazxde',
              't': 't5rfgy6',
              'u': 'u7yhji8',
              'v': 'vfc bg',
              'w': 'w2qasde3',
              'x': 'xszcd',
              'y': 'y6tghu7',
              'z': 'zaZxs',
              ' ': ' bvcnm',
              '"': '"{:?}',
              '\'': '[;/\']',
              ':': ':PL>?"{',
              '<': '<LKM >',
              '>': '>:L<?:',
              ';': ';pl,.;[',
              '[': '[-p;\']=',
              ']': '=[\'',
              '{': '{[_P:"}+',
              '}': '}=[\']=',
              '|': '|\]\'',
              '.': '.l,/;',
              ',': ',lkm.'
            }

    index = random.randint(1,len(word)-1)
    letter = list(word[:index])[-1].lower()
    try:
        if random.random() <= 0.5:
            return word[:index] + random.choice(list(typos[letter])) + word[index:]
        else:
            return word[:index-1] + random.choice(list(typos[letter])) + word[index:]
    except KeyError:
        return word

def generate(self, s, n, safe_name):
    misspelled_s = ''
    misspelled_list = []
    for item in s.split(' '):
        if n:
            if safe_name in item:
                misspelled_list.append(item)
            else:
                r = random.randint(0,1)
                if r == 1 and len(re.sub('[^A-Za-z0-9]+', '', item)) > 3:
                    misspelled_list.append(misspeller(item))
                    n -= 1
                else:
                    misspelled_list.append(item)
        else:
            misspelled_list.append(item)
    return ' '.join(misspelled_list)

Tags: nameindexlenifrandomitem字符else
3条回答

如果你想把一个字母放在字母的前面或后面而不是替换,只需在你的拼接中固定索引,这样它们就不会跳过一个字母,也就是说,使用

x = x[:rnd] + rndCharacter + x[rnd:]

这样,新字符将插入中间,而不是替换现有字符。在

另外,您可以使用rndCharacter = random.choice(characters),而不是像这样使用tmp1。在

import random

def misspeller(word):
    characters = 'qwertyuioplkjhgfdsazxcvbnm,. '
    rand_word_position = random.randint(-1,len(word))
    rand_characters_position = random.randint(0,len(characters)-1)

    if rand_word_position == -1:
        misspelled_word = characters[rand_characters_position] + word 
    elif rand_word_position == len(word):
        misspelled_word = word + characters[rand_characters_position] 
    else:
        misspelled_word = list(word)
        misspelled_word[rand_word_position] = characters[rand_characters_position]
        misspelled_word = ''.join(misspelled_word)        
    return misspelled_word

s = 'Hello how are you today, [name]?'
misspelled_s = ''
misspelled_list = []
for item in s.split(' '):
    if '[name]' in item:
        misspelled_list.append(item)
    else:
        misspelled_list.append(misspeller(item))
misspelled_s = ' '.join(misspelled_list)
print misspelled_s

我从misspelled_s得到的示例是:

^{pr2}$

编辑了以清除第一个副本中的一些错误和遗漏。在

编辑2如果不希望每个单词都受到影响,可以按以下方式修改for循环:

for item in s.split(' '):
    n = random.randint(0,1)
    if '[name]' in item:
        misspelled_list.append(item)
    elif n == 1:
        misspelled_list.append(misspeller(item))
    else:
        misspelled_list.append(item)

您可以通过改变n的生成方式来修改单词被修改的概率,例如n = random.randint(0,10)

我认为@sgallen的答案是可行的,但是我有一些提示(对于您以前的代码,以及以后的代码)。在

for i in range(0, len(arr)):
    x = arr[i]

# is the same as

for i,x in enumerate(arr):

^{pr2}$

使用string作为变量名不是一个好的做法。原因是,有一个string模块。因为string constants,它甚至可能会派上用场。替代品可以是inp,或者{},或者{}。在

# For example

>>> import string
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'

顺便说一下,如果有人注意到上面的错误,请留言。谢谢。在

相关问题 更多 >

    热门问题