Python:从一个列表中搜索字符串的文本,并用另一个

时间:2015-11-24 17:23:38

标签: python string list search

我正在尝试创建一个程序来进行非常简单的加密/压缩。

基本上,程序以句子的形式请求输入,该句子被分成单词,例如

this is the gamma

然后我有两个列表:

mylist1 = ("alpha","beta","gamma","delta")
mylist2 = ("1","2","3","4")

每个单词与包含多个单词的列表匹配。如果列表中存在单词,则应将该单词替换为另一个列表中的相应数字。输出应为:

this is the 3

这是我到目前为止的代码:

text = input("type your sentence \n")
words = text.split(" ")

mylist1 = ("alpha","beta","gamma","delta")
mylist2 = ("1","2","3","4")

#I was looking at zipping the lists together but wasn't sure I was on the right track
#ziplist = zip(mylist1, mylist2) 

for word in words:
    if word in mylist1:
    text = text.replace(word,mylist2[])

print (text)

This question that I was looking into yesterday显示了如何使用字典执行此操作,但在尝试将文本文件从数字再次转换回字时遇到了问题。 (我交换了键和值。我很确定我不应该这样做)

任何输入都很棒。

1 个答案:

答案 0 :(得分:2)

你需要从mylist1获取单词索引,并将变量text中单词的出现替换为mylist2中相同索引处的元素

text = text.replace(word, mylist2[mylist1.index(word)])