2012-01-06 2 views
0

파일을 가져 와서 각 단어의 중간 글자를 임의로 뒤집을 수는 있지만 첫 글자와 마지막 글자를 섞어 쓸 수는 없으며 3 글자 이상 뒤섞습니다. . 모든 글자가 분리되어있는 각자의 목록에 각 단어를 넣을 수 있다면 그들을 뒤섞을 수있는 방법을 찾아 낼 수 있다고 생각합니다. 어떤 도움을 주시면 감사하겠습니다. 감사.파일을 가져 와서 중간의 모든 문자를 섞습니다.

+5

임의 가져와야

'

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

주위에 편지를 셔플이 같은 일을 할 수 있습니까? 정확히 어디에서 문제가 있습니까? 그것을 분해하고, 코드를 작성해보십시오. 실제로 대답할만한 질문은 없습니다. – Yuushi

답변

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 

셔플 알고리즘은 의도적으로 구현되지 않았습니다.

+0

나는 조금 혼란 스럽다. 실제로 주위의 모든 것을 뒤섞 지 않고 단어 자체에 공백을 만듭니다. – Makoto

+0

@Makoto, "모든 글자가 분리되어있는 각 단어를 각기 다른 목록에 넣을 수 있다면 그들을 뒤섞을 수있는 방법을 찾아 낼 수 있다고 생각합니다." 나는 완전한 문제를 해결하고 싶지 않았습니다. :-) –

+1

충분히 공정하고 (그리고 완전히 정당한). 회신에서 무언가를 편집하여 그 downvote를 취소 할 수 있습니다. – Makoto

0

random.shuffle을 살펴보십시오. 그것은 당신이 목표로하는 것으로 보이는 목록 개체를 섞습니다. 당신은 그래서 당신이해야 할 노력 무엇을

+0

고마워. Random.shuffle은 매우 유용했습니다 =) – Albo

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

개행 문자를 보존하고 싶지 않다고 생각했습니다. 그렇게했다면 get_words()에서 간단히 반환하십시오. –