Python:在文本中搜索一个列表中的字符串,然后将其替换为另一个列表中的字符串 [英] Python: Searching text for Strings from one List and replacing them with Strings from another

查看:79
本文介绍了Python:在文本中搜索一个列表中的字符串,然后将其替换为另一个列表中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a program to do very simple encryption/compression.

基本上,该程序以句子形式请求输入,该句子被分解为多个单词,例如

Basically, the program requests input in the form of a sentence which is split into words, e.g.

this is the gamma

然后我有两个列表:

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

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

Each word is matched against a list which contains a number of words. if the words are present in the list then it should replace the word with the corresponding number in the other list. The output should be:

this is the 3

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

Here is the code I have so far:

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 shows how to do this using a dictionary but I encountered a problem when trying to convert the text file back from numbers to words again. (I swapped the Keys and Values around. I'm pretty certain I shouldn't do that)

任何输入都是很棒的.

推荐答案

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

You need to get the index of word from mylist1 and replace the occurrence of word in the variable text with the element at that same index in mylist2

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

这篇关于Python:在文本中搜索一个列表中的字符串,然后将其替换为另一个列表中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆