2014-02-17 3 views
0

모음에 '0'값을 받고 자음에 '1'값이있는 모음 및 자음 내용을 기반으로 단어의 이진 값을 만들려고합니다.파이썬에서 문자열을 이진 표현으로 변환

>>>dictify 
{'aardvark': [0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1,...} 

원하는 : 예를 들어

은 '하하'나는 결과 사전에 너무 많은 이진수를 얻고이 가진 - 101010.

common_words = ['haha', 'hahaha', 'aardvark', etc...] 

dictify = {} 

binary_value = [] 

#doesn't work 
for word in common_words: 
    for x in word: 
     if x=='a' or x=='e' or x=='i' or x=='o' or x=='u': 
      binary_value.append(0) 
      dictify[word]=binary_value 
     else: 
      binary_value.append(1) 
      dictify[word]=binary_value 

로 하하하, 1010로 표현된다 출력 :

>>>dictify 
{'haha': 1010,'hahaha': 101010, 'aardvark': 00111011} 

루프 내에서 루프를 포함하지 않는 해결책을 생각 중입니다 ...

+0

여기서 'each'또는 'number_value'는 어디에서 오는가요? – user2357112

+1

두 개의 루프를 사용하지 않는 솔루션은 없습니다. – placeybordeaux

+0

'dictify = {w : "". join ('aeiouAEIOU'에 c가있는 경우 '0'이면 c에 대해 1을 사용합니다) common_words에서 ' – mshsayem

답변

2

모든 단어가 동일한 binary_value 목록을 공유하기 때문에 게시 한 코드가 작동하지 않습니다. (number_valueeach이 정의되지 않기 때문에 그것은 또한 작동하지 않습니다,하지만 우리는 그 변수 대신 binary_valueword 말했다 척 수 있습니다.) 각 단어에 대한 새로운 목록을 정의 : 사용자가 출력을 원하는 경우에

for word in common_words: 
    binary_value = [] 
    for x in word: 
     if x=='a' or x=='e' or x=='i' or x=='o' or x=='u': 
      binary_value.append(0) 
      dictify[word]=binary_value 
     else: 
      binary_value.append(1) 
      dictify[word]=binary_value 

목록이 아닌 00111011처럼 보이면 문자열을 만들어야합니다. (당신은 int를 만들 수 있지만, 그때는 59 대신 00111011과 같을 것이다. 파이썬은 "이 INT는 기본 2"구분하지 않습니다 또는 "이 INT는이 앞의 0이 있습니다.")

for word in common_words: 
    binary_value = [] 
    for x in word: 
     if x.lower() in 'aeiou': 
      binary_value.append('0') 
     else: 
      binary_value.append('1') 
    dictify[word] = ''.join(binary_value) 
2

user2357112 설명 당신의 코드. 다음은 다른 방법입니다.

>>> common_words = ['haha', 'hahaha', 'aardvark'] 
>>> def binfy(w): 
     return "".join('0' if c in 'aeiouAEIOU' else '1' for c in w) 

>>> dictify = {w:binfy(w) for w in common_words} 
>>> dictify 
{'aardvark': '00111011', 'haha': '1010', 'hahaha': '101010'} 
1

번역 테이블의 작업처럼 보입니다. 가정 사용자의 입력 문자열의 모든 ASCII이다 (그리고 보인다 또는 취득 퍼지 모음 정확히의 정의), 당신은 변환 테이블이 방법 * 정의 할 수 있습니다 : 위의 표와

# For simplicity's sake, I'm only using lowercase letters 
from string import lowercase, maketrans 
tt = maketrans(lowercase, '01110111011111011111011111') 

을 문제가된다 사소한 :이 솔루션을 감안할 때

>>> 'haha'.translate(tt) 
'1010' 
>>> 'hahaha'.translate(tt) 
'101010' 
>>> 'aardvark'.translate(tt) 
'00111011' 

, 당신은 이해 매우 간단 dictify을 구축 할 수 있습니다 :

dictify = {word:word.translate(tt) for word in common_words} #python2.7 
dictify = dict((word, word.translate(tt)) for word in common_words) # python 2.6 and earlier 

*이 또한 파이썬 3으로 수행 할 수 있습니다,하지만 당신은 바이트 난을 사용해야합니다 문자열의 배열 :

from string import ascii_lowercase 
tt = b''.maketrans(bytes(ascii_lowercase, 'ascii'), b'01110111011111011111011111') 
b'haha'.translate(tt) 
... 
관련 문제