使用正则表达式:
import random
import re
random.seed(1234) #remove this in production, just for replication of my results
def shuffle_word(m):
word = m.group()
inner = ''.join(random.sample(word[1:-1], len(word) - 2))
return '%s%s%s' % (word[0], inner, word[-1])
s = """This is 'Cambridge University' for example."""
print re.sub(r'\b\w{3}\w+\b', shuffle_word, s)
哪个打印
Tihs is 'Cadibrgme Uinrtvsiey' for exlampe.
re.sub
允许您向它传递一个函数(它接受一个正则表达式匹配对象)而不是替换字符串。
编辑 - 没有正则表达式
from StringIO import StringIO
def shuffle_word(m):
inner = ''.join(random.sample(m[1:-1], len(m) - 2))
return '%s%s%s' % (m[0], inner, m[-1])
def scramble(text)
sio = StringIO(text)
accum = []
start = None
while sio.tell() < sio.len:
char = sio.read(1)
if start is None:
if char.isalnum():
start = sio.tell() - 1
else:
accum.append(char)
elif not char.isalnum():
end = sio.tell() - 1
sio.seek(start)
accum.append(shuffle_word(sio.read(end - start)))
print accum[-1]
start = None
else:
if start is not None:
sio.seek(start)
word = sio.read()
if len(word) > 3:
accum.append(shuffle_word(sio.read()))
else:
accum.append(word)
return ''.join(accum)
s = """This is 'Cambridge University' for example."""
print scramble(s)