举例来说,我有以下字符串:将随机字符字符串,如果没有一定的单词
Hello how are you today, [name]?
字的随机选择,但不是[名]之间我怎么会去随意放置字符?我已经有了下面这段代码,但我希望有更好的方法去实现它。
string = 'Hello how are you today, [name]?'
characters = 'qwertyuioplkjhgfdsazxcvbnm,. '
arr = string.rsplit(" ")
for i in range(0, len(arr)):
x = arr[i]
if x == '[name]':
continue
if (random.randint(0,2)==1) :
rnd=random.randint(1,len(x)-2)
tmp1 = random.randint(0,len(characters))
rndCharacter = characters[tmp1:tmp1+1]
x = x[0:rnd] + rndCharacter + x[rnd+1:]
arr[i] = x
" ".join(arr)
> Hellio how are yoy todsy, [name]?"
虽然这会用另一个随机字符替换字符。我会以什么方式随机替换或在角色之前或之前放置一个随机角色?
基本上我只是想模拟一种错字发生器。
感谢
在我的代码更新至今:
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]?
UPDATE:
也许我的代码最后的更新,希望这将帮助别人出一些点在未来
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)
从输入“你好,你今天怎么样,[名字]? ? – FakeRainBrigand
对不起,像这样的东西“Hellio怎么样,同性恋,[姓名]?” – mikeyy
那么'[name]'实际上是在括号内吗?或者名字会成为一个真实的名字,比如'today,mike'? (有时候人们会在占位符不会真正出现在输入中时使用占位符。) – FakeRainBrigand