读取文件并打乱中间所有字母
我需要处理一个文件,把每个单词中间的字母打乱,但不能动第一个和最后一个字母,而且只对长度超过3个字母的单词进行打乱。我觉得如果能把每个单词放到一个单独的列表里,把字母分开,就能找到打乱它们的方法。希望能得到一些帮助。谢谢!
3 个回答
0
#with open("words.txt",'w') as f:
# f.write("one two three four five\nsix seven eight nine")
def get_words(f):
for line in f:
for word in line.split():
yield word
import random
def shuffle_word(word):
if len(word)>3:
word=list(word)
middle=word[1:-1]
random.shuffle(middle)
word[1:-1]=middle
word="".join(word)
return word
with open("words.txt") as f:
#print list(get_words(f))
#['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
#print map(shuffle_word,get_words(f))
#['one', 'two', 'trhee', 'four', 'fvie', 'six', 'sveen', 'eihgt', 'nnie']
import tempfile
with tempfile.NamedTemporaryFile(delete=False) as tmp:
tmp.write(" ".join(map(shuffle_word,get_words(f))))
fname=tmp.name
import shutil
shutil.move(fname,"words.txt")
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
0
看看random.shuffle这个函数。它可以直接在原来的列表上打乱顺序,这正是你想要的效果。你可以用下面的方式来打乱字母的顺序。
`
def scramble(word):
output = list(word[1:-1])
random.shuffle(output)
output.append(word[-1])
return word[0] + "".join(output)`
记得要先导入random这个模块哦。
3
text = "Take in a file and shuffle all the middle letters in between"
words = text.split()
def shuffle(word):
# get your word as a list
word = list(word)
# perform the shuffle operation
# return the list as a string
word = ''.join(word)
return word
for word in words:
if len(word) > 3:
print word[0] + ' ' + shuffle(word[1:-1]) + ' ' + word[-1]
else:
print word
洗牌算法故意没有实现。