📜  Python – 替换字典中的单词

📅  最后修改于: 2022-05-13 01:55:29.642000             🧑  作者: Mango

Python – 替换字典中的单词

给定字符串,从查找字典中替换它的单词。

方法#1:使用 split() + get() + join()

在此,我们最初使用 split() 拆分列表,然后使用 get() 查找查找,如果找到,则使用 join() 替换并连接回字符串。

Python3
# Python3 code to demonstrate working of 
# Replace words from Dictionary
# Using split() + join() + get()
  
# initializing string
test_str = 'geekforgeeks best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# lookup Dictionary
lookp_dict = {"best" : "good and better", "geeks" : "all CS aspirants"}
  
# performing split()
temp = test_str.split()
res = []
for wrd in temp:
      
    # searching from lookp_dict
    res.append(lookp_dict.get(wrd, wrd))
      
res = ' '.join(res)
  
# printing result 
print("Replaced Strings : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Replace words from Dictionary
# Using list comprehension + join()
  
# initializing string
test_str = 'geekforgeeks best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# lookup Dictionary
lookp_dict = {"best" : "good and better", "geeks" : "all CS aspirants"}
  
# one-liner to solve problem
res = " ".join(lookp_dict.get(ele, ele) for ele in test_str.split())
  
# printing result 
print("Replaced Strings : " + str(res))


输出
The original string is : geekforgeeks best for geeks
Replaced Strings : geekforgeeks good and better for all CS aspirants

方法 #2:使用列表理解 + join()

与上述方法类似,区别只是 1 行而不是 3-4 步在单独的行中。

Python3

# Python3 code to demonstrate working of 
# Replace words from Dictionary
# Using list comprehension + join()
  
# initializing string
test_str = 'geekforgeeks best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# lookup Dictionary
lookp_dict = {"best" : "good and better", "geeks" : "all CS aspirants"}
  
# one-liner to solve problem
res = " ".join(lookp_dict.get(ele, ele) for ele in test_str.split())
  
# printing result 
print("Replaced Strings : " + str(res)) 
输出
The original string is : geekforgeeks best for geeks
Replaced Strings : geekforgeeks good and better for all CS aspirants