简体   繁体   English

我想用 Python 中的字母替换单词

[英]I Would Like To Replace A Word With A Letter In Python

Code:代码:

list = ['hello','world']
list2 = ['a','b']
string = 'hello'# should output a 
string_fin = ''
for s in string:
    for i, j in zip (list, list2):
        if s == i:
            string_fin += j
print(string_fin)

I want to write hello or world in string = '' and to get the output a or b我想在string = ''中写hello or world并获得 output a or b

I get我明白了 which is nothing这没什么

The reason this is happening is because hello and world have more characters than a and b when I try something that has the same amount of characters as a or b it works发生这种情况的原因是因为当我尝试使用与a or b具有相同数量字符的东西时, hello and world的字符比a and b

Please help请帮忙

Thanks谢谢

Better to store your lists as a dictionary, so you can do an easy lookup:最好将列表存储为字典,这样您就可以轻松查找:

mapping = {'hello':'a', 'world':'b'}
string = 'hello or world'
out = []
for s in string.split():
    out.append( mapping.get( s, s ) )
print(' '.join(out))

Purists will note that the for loop can be made into a one-liner:纯粹主义者会注意到for循环可以做成单行代码:

mapping = {'hello':'a', 'world':'b'}
string = 'hello or world'
out = ' '.join(mapping.get(s,s) for s in string.split())
print(out)

Your program's main loop never runs because string is empty: So your program is basically:你的程序的主循环永远不会运行,因为string是空的: 所以你的程序基本上是:

list = ['hello','world']
list2 = ['a','b']
string = ''
string_fin = ''
print(string_fin)

Although based on how you worded your question, it is really hard to understand what you are trying to accomplish, but here is my go.虽然根据你的问题措辞,真的很难理解你想要完成的事情,但这是我的 go。

  • You have two lists: list1 and list2 ( Please do not name your list list as it is a reserved keyword, use list1 instead! )您有两个列表: list1list2请不要命名您的列表list ,因为它是保留关键字,请改用list1
  • You want to check whether each word in your string matches with any word in your first list.您想要检查string中的每个单词是否与第一个列表中的任何单词匹配。
  • If it matches you want to take the corresponding word or letter from your second list, and append it into the string string_fin .如果它匹配,你想从你的第二个列表中获取相应的单词或字母,并将它的string_fin放入字符串 string_fin 中。
  • Finally, when you looped through all the words in the list, you print the content of string_fin .最后,当您遍历列表中的所有单词时,打印string_fin的内容。

The correct way to do this would be to split your string variable, and get each word stored in it.执行此操作的正确方法是拆分string变量,并将每个单词存储在其中。

string = 'hello or world'
stringWords = string.split()

Now, stringWords contains ['hello', 'or', 'world'] .现在, stringWords包含['hello', 'or', 'world'] But I think you are not interested in the item or .但我认为您对该项目or不感兴趣。 So you can remove this item from the list, by using remove() .因此,您可以使用remove()从列表中删除此项。

if 'or' in stringWords:
    stringWords.remove('or')

Now you have the words that you are interested in. And we want to check whether any word in the first list matches with these words.现在您有了感兴趣的词。我们要检查第一个列表中的任何词是否与这些词匹配。 (Remember, I renamed the first list from list to list1 to prevent any unexpected behavior.) (请记住,我将第一个列表从list重命名为list1以防止任何意外行为。)

for word in stringWords:
    tempIndex = list1.index(word)
    temp = list2[tempIndex]
    string_fin += temp

However, using index raises ValueError if a match is not found, so depending on your program logic, you may need to catch an exception and handle it.但是,如果未找到匹配项,使用index会引发ValueError ,因此根据您的程序逻辑,您可能需要捕获异常并进行处理。 The string string_fin will now contain ab or a or b depending on the value inside string .字符串string_fin现在将包含abab ,具体取决于string中的值。

Now, since you wanted to print something like a or b , you can instead create a list and store the matching words in it, and then, join this list using or separator.现在,由于您想打印类似a or b内容,您可以创建一个列表并将匹配的单词存储在其中,然后使用or分隔符加入此列表。

string_fin = (' or ').join(tempList)

A complete program now will look like this:一个完整的程序现在看起来像这样:

list1 = ['hello', 'world']
list2 = ['a', 'b']
string = 'hello or world'
tempList = []
stringWords = string.split()

if 'or' in stringWords:
    stringWords.remove('or')

for word in stringWords:
    tempIndex = list1.index(word)
    temp = list2[tempIndex]
    tempList.append(temp)

string_fin = ' or '.join(tempList)
print(string_fin)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM