<pre><code>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
</code></pre>
<p>我从<code>misspelled_s</code>得到的示例是:</p>
^{pr2}$
<p><strong>编辑了</strong>以清除第一个副本中的一些错误和遗漏。在</p>
<p><strong>编辑2</strong>如果不希望每个单词都受到影响,可以按以下方式修改for循环:</p>
<pre><code>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)
</code></pre>
<p>您可以通过改变<code>n</code>的生成方式来修改单词被修改的概率,例如<code>n = random.randint(0,10)</code></p>