gpt4 book ai didi

python - 在 Python 中使用字典替换列表中的字符串

转载 作者:行者123 更新时间:2023-12-01 22:51:28 25 4
gpt4 key购买 nike

如何使用字典替换列表中的字符串?

我有

text = ["h#**o+","+&&&orld"]
replacement = {"#":"e","*":"l","+":"w","&":""}

我要:

correct = ["Hellow 
World"]

我试过了:

def correct(text,replacement):
for word, replacement in replacement.items():
text = text.replace(word, replacement)

但是:AttributeError: 'list' 对象没有属性 'replace'

最佳答案

除了你的 correct 函数似乎只想更正一个 str (例如 "h#**o+" => "hellow"),而您的变量 text 当前是 liststr。因此,如果你想获得 "hellow world",你需要多次调用 correct 以获得更正单词的列表,然后你可以将其加入一个字符串。

试试这个可运行的例子!

#!/usr/bin/env python

words = ["h#**o+","+&&&orld"]
replacement = {"#":"e","*":"l","+":"w","&":""}

def correct(text,replacement):
for word, replacement in replacement.items():
text = text.replace(word, replacement)
return text

def correct_multiple(words, replacement):
new_words = [correct(word, replacement) for word in words] # get a list of results
combined_str = " ".join(new_words) # join the list into a string
return combined_str

output = correct_multiple(words, replacement)
print(f"{output=}")
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

关于python - 在 Python 中使用字典替换列表中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74256470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com