/ / मैं एक शब्दकोश से मूल्यों के साथ एक स्ट्रिंग कैसे बदल सकता हूं अजगर - अजगर

मैं एक स्ट्रिंग को एक शब्दकोश से मूल्यों के साथ कैसे बदलूं? पायथन - पायथन

मेरा कोड ...

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

उत्तर:

जवाब के लिए 2 № 1

इसे इस्तेमाल करे:

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))

उत्तर № 2 के लिए 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))

जवाब के लिए 0 № 3

प्रतिस्थापन का क्रम महत्वपूर्ण है। आपके मामले में:

  • कब 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])