2017-05-03 1 views
0

내 코드 ... 문자열을 사전의 값으로 바꾸려면 어떻게합니까? 파이썬

sentence = "hello world helloworld" 

dictionary = {"hello": "1", "world": "2", "helloworld": "3"} 

for key in dictionary: 
    sentence = sentence.replace(key, dictionary[key]) 

print(sentence) 

는 내가 뭘 원하는 ...

실제로 무엇을
1 2 3 

...

1 2 12 
+0

지정하십시오, 경우 '에만 사전에서 단어를 포함 sentence' 또는 다른 단어가 가능하다면. 또한 현재 양식에서 오류가 발생합니다 :'AttributeError : 'list'객체에는 'replace'' 속성이 없습니다. –

+0

내 문장에는 사전의 단어 만 포함됩니다. –

답변

2

이 시도 :

sentence = "hello world helloworld" 
sentence = sentence.split() 

dictionary = {"hello": "1", "world": "2", "helloworld": "3"} 

print ' '.join(map(lambda x: dictionary.get(x) or x , sentence)) 
+0

'sentence'에 가능한 단어가 실제로 사전에 존재할 때 작동합니다. –

+0

@ ChristianKönig, edited. 제안 해 주셔서 감사합니다. –

+0

or-approach를 정말 좋아합니다. +1 –

0

repl acements는 중요합니다. 귀하의 경우 :

  • hello를 교체 할 때 : "1 세계 1world"
  • world 처음 교체하는 경우 : "1 2 (12)는"

그것의 명령으로 키를 반복 피하기 위해 자신의 길이. 가장 긴 것에서 가장 짧은 것. 문장이 변경되지 반환해야 당신의 사전에서 단어를하지 포함 할 경우

for key in dictionary.keys().sort(lambda aa,bb: len(aa) - len(bb)): 
    sentence = sentence.replace(key, dictionary[key]) 
1

,이 방법을 시도해보십시오

sentence = "hello world helloworld missing words" 
sentence = sentence.split() 

dictionary = {"hello": "1", "world": "2", "helloworld": "3"} 

for i, word in enumerate(sentence): 
    sentence[i] = dictionary[word] if word in dictionary else word 

print(" ".join(sentence)) 
관련 문제