回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>例如,我有以下字符串:</p>
<pre><code>Hello how are you today, [name]?
</code></pre>
<p>我该如何在随机选择的单词之间随机地放置字符,而不是[name]?我已经有了下面这段代码,但我希望有更好的方法来实现它。在</p>
^{pr2}$
<p>虽然这会用另一个随机字符替换这个字符。我该用什么方法让它随机替换或者在一个字符之后或之前放置一个随机字符?在</p>
<p>基本上我只是想模拟一种打字错误生成器。在</p>
<p>谢谢</p>
<p>到目前为止我的代码更新:</p>
<pre><code>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]?
</code></pre>
<p>更新:</p>
<p>也许我对代码的最后更新,希望这能在将来帮助别人解决一些问题</p>
<pre><code>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.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(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)
</code></pre>