我正在尝试创建一个简单的程序,让您输入一个句子,然后将其拆分为单个单词,保存为分割线.例如:
the man lives in a house
每个单词将与一个dict相匹配,该dict包含针对以下值存储的多个单词:
mydict = {"the":1,"in":2,"a":3}
如果单词存在于dict中,那么我希望用与该值关联的键替换该单词,以便输出看起来像:
1 man lives 2 3 house
我创建了一些代码,允许我测试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)
似乎我不能将splitline.replace与dict.keys(mydict)一起使用,因为我认为它将选择所有的键,而不仅仅是我想要处理的实例.有没有办法可以做到这一点?
我希望我已经正确地解释了自己.
解决方法:
我不确定你为什么要迭代每一个角色,每次都指定splitline是同一个东西.我们不要那样做.
words = text.split() # what's a splitline, anyway?
看起来你的术语是倒退的,字典看起来像:{key:value}不像{value:key}.在这种情况下:
my_dict = {'the': 1, 'in': 2, 'a': 3}
将“男人住在一个房子里”变成“男人生活2 3房子”是完美的
从那里你可以使用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
如果键不在字典中,则dict.get允许您指定默认值(而不是像dict [key]那样引发KeyError).在这种情况下,你说“给我关键词的价值,如果它不存在,只要给我一个字”
标签:python,list,dictionary,replace
来源: https://codeday.me/bug/20191009/1876354.html