如何使用字典替换列表中的字符串?
我有
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
当前是list
或str
s之外,您所拥有的基本都是正确的。因此,如果您想获得"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>
您也可以这样做:
text = ["h#**o+","+&&&orld"]
replacement = {"#":"e","*":"l","+":"w","&":""}
string1 = " ".join(text) # join the words into one string
string2 = string1.translate(string1.maketrans(replacement))
string3 = string2.title()
print(string1 + 'n' + string2 + 'n' + string3)
# h#**o+ +&&&orld
# hellow world
# Hellow World
我将程序分为三个连续的步骤,以展示每个步骤的效果。
text
是字符串列表,而不是字符串。你不能在上面调用字符串方法。
text[0].replace()
将是一件。。。