Возьмите файл и перемешайте все средние буквы между - PullRequest
0 голосов
/ 06 января 2012

Мне нужно взять файл и перетасовать средние буквы каждого слова, но я не могу перетасовать первые и последние буквы, и я перетасовываю слова длиннее 3 символов. Я думаю, что смогу найти способ перетасовать их, если бы я мог поместить каждое слово в отдельный список, где все буквы разделены. Любая помощь будет оценена. Спасибо.

Ответы [ 3 ]

3 голосов
/ 06 января 2012
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

Алгоритм тасования намеренно не реализован.

0 голосов
/ 06 января 2012
#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 голосов
/ 06 января 2012

Посмотрите на random.shuffle. Он перетасовывает объект списка на место, которое, кажется, является тем, к чему вы стремитесь. Вы можете сделать что-то вроде этого, чтобы перетасовывать буквы вокруг

`

def scramble(word):

    output = list(word[1:-1])
    random.shuffle(output)
    output.append(word[-1])
    return word[0] + "".join(output)`

Только не забудьте импортировать случайные

...