mjo*_*nir 2 python dictionary replace list
我正在尝试创建一个简单的程序,让您输入一个句子,然后将其拆分为单个单词,保存为splitline.例如:
the man lives in a house
Run Code Online (Sandbox Code Playgroud)
每个单词将与一个dict相匹配,该dict包含针对以下值存储的多个单词:
mydict = {"the":1,"in":2,"a":3}
Run Code Online (Sandbox Code Playgroud)
如果单词存在于dict中,那么我希望用与该值关联的键替换该单词,以便输出看起来像:
1 man lives 2 3 house
Run Code Online (Sandbox Code Playgroud)
我创建了一些代码,允许我测试dict中是否存在每个单词,然后能够为句子中的每个单词输出'true'或'false',但是当我尝试用dict中的键替换单词时goit有点卡住了.
这是我到目前为止所尝试的:
text = input("Enter a sentence \n")
for word in text:
splitline = text.split(" ")
mydict = {"the":1,"in":2,"a":3}
for word in splitline:
if word in dict.keys(mydict):
#I tried to declare x as the value from the dict
x = str(dict.values(mydict))
#newline should be the original splitline with word replaced with x
newline = splitline.replace(word,x)
#the program should print the newline with word replaced with key
print(newline)
Run Code Online (Sandbox Code Playgroud)
似乎我不能使用splitline.replace,dict.keys(mydict)因为我认为它将选择所有的键而不仅仅是我想要处理的实例.有没有办法可以做到这一点?
我希望我已经正确地解释了自己.
我不确定你为什么要迭代每一个角色,每次分配splitline都是同一个东西.我们不要那样做.
words = text.split() # what's a splitline, anyway?
Run Code Online (Sandbox Code Playgroud)
看起来你的术语是倒退的,字典看起来像:{key: value}不喜欢{value: key}.在这种情况下:
my_dict = {'the': 1, 'in': 2, 'a': 3}
Run Code Online (Sandbox Code Playgroud)
是完美的"the man lives in a house"变成"1 man lives 2 3 house"
从那里你可以使用dict.get.我不推荐str.replace.
final_string = ' '.join(str(my_dict.get(word, word)) for word in words)
# join with spaces all the words, using the dictionary substitution if possible
Run Code Online (Sandbox Code Playgroud)
dict.get如果键不在字典中,则允许您指定默认值(而不是提高KeyError类似值dict[key]).在这种情况下,你说"给我钥匙的价值word,如果它不存在就给我word"