【问题标题】:Python: Searching text for Strings from one List and replacing them with Strings from anotherPython:从一个列表中搜索字符串并用另一个列表中的字符串替换它们
【发布时间】:2015-11-24 17:23:37
【问题描述】:

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

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

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 展示了如何使用字典执行此操作,但我在尝试将文本文件再次从数字转换回单词时遇到了问题。 (我交换了键和值。我很确定我不应该这样做)

任何输入都会很棒。

【问题讨论】:

    标签: python string list search


    【解决方案1】:

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

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

    【讨论】:

    • 索引!,哦。我不知道如何链接它们。你可以说我还在学习。你有点传奇。谢谢。
    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 2020-01-06
    • 2012-08-18
    • 2019-07-27
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多