2011-09-12 7 views
-3

가능한 중복 :
Overriding the newline generation behaviour of Python's print statement
PPM image to ASCII art in Python파이썬 목록 질문

이 내 코드, 난 문자가 인쇄 있지만 나는 그들이 같은 줄에과에서 휴식 필요 라인의 끝.

import sys 

def main(filename): 
    image = open(filename) 
    #reads through the first three lines 
    color = image.readline().splitlines() 
    size_width, size_height = image.readline().split() 
    max_color = image.readline().splitlines() 

    #reads the body of the file 
    pixels = image.read().split() 
    red = 0 
    green = 0 
    blue = 0 
    r_g_b_value = [] 
    #pulls out the values of each tuple and coverts it to its grayscale value 
    for i in pixels: 
     if i != "\n" or " ": 
     if len(i) == 3: 
      red = int(i[0]) * .3 
      green = int(i[1]) * .59 
      blue = int(i[2]) * .11 
     elif len(i) == 2: 
      red == int(i[0]) 
      green == int(i[1]) 
      blue == 0 
     elif len(i) == 1: 
      red == int(i[0]) 
      green == 0 
      blue == 0 

     r_g_b_value = [red + green + blue] 
     grayscale = [] 
     character = [] 

     for j in r_g_b_value: 
      if int(j) <= .2: 
       character = "M" 
      elif int(j) > .2 and int(j) <= .4: 
       character = "#" 
      elif int(j) > .4 and int(j) <= .6: 
       character = "A" 
      elif int(j) > .6 and int(j) <= .8: 
       character = "@" 
      elif int(j) > .8 and int(j) <= 1: 
       character = "$" 
      elif int(j) > 1 and int(j) <= 1.2: 
       character = "0" 
      elif int(j) > 1.2 and int(j) <= 1.4: 
       character = "e" 
      elif int(j) > 1.4 and int(j) <= 1.6: 
       character = "a" 
      elif int(j) > 1.8 and int(j) <= 2: 
       character = "o" 
      elif int(j) > 2 and int(j) <= 2.2: 
       character = "=" 
      elif int(j) > 2.25 and int(j) <= 2.5: 
       character = "+" 
      elif int(j) > 2.5 and int(j) <= 2.75: 
       character = ";" 
      elif int(j) > 2.75 and int(j) <= 3: 
       character = ":" 
      elif int(j) > 3 and int(j) <= 3.4: 
       character = "," 
      elif int(j) > 3.4 and int(j) <= 3.9: 
       character = "." 
      else: 
       character = " " 
      character += character 
      grayscale = [character] 
      print(grayscale) 

어떤 도움을 주시면 감사하겠습니다.

+12

이 코드는 나를 깜짝 놀라게합니다! –

+0

이전의 특정 질문이 실제로는 좋은 phooji라고 생각하지 마십시오. – Amber

+0

@asmith : 귀하의 질문을 오래된 stackoverflow 질문의 중복으로 표시했습니다. 또한 본질적으로 매우 유사한 많은 질문을 던집니다. 이것은 권장하지 않습니다 (http://blog.stackoverflow.com/2009/04/a-day-in-the-penalty-box/). – phooji

답변

3

은 빈 문자열이 될하기 위해 end parameter for print()을 지정하고 자동 줄 바꿈 추가하지 않습니다 :

>>> print('foo', end=''); print('bar'); print('baz') 
foobar 
baz 

end의 기본값은 '\n'입니다; print()에 전달 된 모든 일반 인수가 출력 된 후에 end이 추가됩니다. 예를 들어 print('foo', 'bar'); print('baz')은 위와 동일하게 출력됩니다.

인쇄 할 각 개체 사이에 추가되는 sep 매개 변수도 있습니다 (la join()). 기본값은 nothing입니다. 이 정도의 간단한 코드

for j in r_g_b_value: 
     if int(j) <= .2: 
      character = "M" 
     elif int(j) > .2 and int(j) <= .4: 
      character = "#" 
     elif int(j) > .4 and int(j) <= .6: 
      character = "A" 
     elif int(j) > .6 and int(j) <= .8: 
      character = "@" 
     elif int(j) > .8 and int(j) <= 1: 
      character = "$" 
     elif int(j) > 1 and int(j) <= 1.2: 
      character = "0" 
     elif int(j) > 1.2 and int(j) <= 1.4: 
      character = "e" 
     elif int(j) > 1.4 and int(j) <= 1.6: 
      character = "a" 
     elif int(j) > 1.8 and int(j) <= 2: 
      character = "o" 
     elif int(j) > 2 and int(j) <= 2.2: 
      character = "=" 
     elif int(j) > 2.25 and int(j) <= 2.5: 
      character = "+" 
     elif int(j) > 2.5 and int(j) <= 2.75: 
      character = ";" 
     elif int(j) > 2.75 and int(j) <= 3: 
      character = ":" 
     elif int(j) > 3 and int(j) <= 3.4: 
      character = "," 
     elif int(j) > 3.4 and int(j) <= 3.9: 
      character = "." 
     else: 
      character = " " 

:

# Mapping of values to symbol tuples, ordered from least to greatest upper bound. 
# Format is (symbol, upperbound) - lower bounds are implied by 
# the previous symbol's upper bound, non-inclusive. 
symbol_set = [('M', 0.2), ('#', 0.4), ('A', 0.6), ('@', 0.8), ('$', 1.0), 
    ('0', 1.2), ('e', 1.4), ('a', 1.6), ('o', 2.0), ('=', 2.2), ('+', 2.5), 
    (';', 2.75), (':', 3.0), (',', 3.4), ('.', 3.9)] 

for j in r_g_b_value: 
    for symbol, cutoff in symbol_set: 
     if j <= cutoff: 
      character = symbol 
      break 
    else: 
     character = ' ' 

합니다 (for: else: 건설은 단지이 경우했다 "을 의미 그런데


, 아래의 전체 블록을 다시 작성할 수 있습니다 루프에서 break이 실행되지 않으면 else: 섹션에있는 작업을 수행하고 이전 코드에서 'else'사례를 처리합니다.

컴퓨터가 항상 당신을 위해 일하도록 노력해야합니다. 거의 동일한 elif 절을 10-15 개 작성하는 대신 루프를 사용하도록 약간의 영리함을 사용하십시오.

+0

아마도 bisect (http://docs.python.org/library/bisect.html#other-examples)를 사용하는 것이 더 좋은 옵션입니다 –

+0

예, 'bisect'는 루프를 작성하는 훨씬 간결한 방법입니다 - 단점은 기호 집합에 대해 다른 형식이 필요하다는 것입니다 (단락의 개별 배열과 색인이 매핑되어야하는 것들). 위에서 사용 된리스트 형식 ('symbols = [x는 symbol_set에서 x에 대해 x [0] '),'cutoffs = [x [symbol_set에서 x에 대해 x [1]]에서 두리스트를 생성 할 수 있지만, 어느 쪽이든 많은 일에 관해서. 실제로 데이터를 지정하는 방식을 결정할 때가 있습니다. – Amber

+0

'symbols, cutoffs = zip (* symbol_set) ' –