我有两个这样的字符串。
string1 = "Today I went to the (market) to pick up some (fruit)."
string2 = "Today I went to (school) to learn (algebra) and science."
我想根据以下字典在两个字符串中删除并替换括号和括号内的文本。
word_dict = {'market': 'library', 'fruit': 'books', 'school': 'class', 'algebra': 'calculus'};
我希望新的字符串是:
string1 = "Today I went to the library to pick up some books."
string2 = "Today I went to class to learn calculus and science."
为此,我需要在括号内捕获文本,以便可以将其用作获取字典中值的键。然后,我需要用该值替换括号和文本。我在使用正则表达式以及如何执行此操作时遇到了麻烦。
您可以使用str.replace()
:
string1 = "Today I went to the (market) to pick up some (fruit)."
string2 = "Today I went to (school) to learn (algebra) and science."
word_dict = {'market': 'library', 'fruit': 'books', 'school': 'class', 'algebra': 'calculus'}
for word, translation in word_dict.items(): # Use word_dict.iteritems() for Python 2
string1 = string1.replace('(' + word + ')', translation)
string2 = string2.replace('(' + word + ')', translation)
你也可以使用str.format()
,如果你能控制的初始字符串使用{}
,而不是()
:
string1 = "Today I went to the {market} to pick up some {fruit}."
string2 = "Today I went to {school} to learn {algebra} and science."
word_dict = {'market': 'library', 'fruit': 'books', 'school': 'class', 'algebra': 'calculus'}
string1 = string1.format(**word_dict)
string2 = string2.format(**word_dict)
如果你无法控制的初始输出,但想用str.format()
反正,你可以替换的任何事件(
,并)
用{
和}
:
string1 = string1.replace('(', '{').replace(')', '}').format(**word_dict)
string2 = string2.replace('(', '{').replace(')', '}').format(**word_dict)
或以更简洁的方式执行此操作,可以str.translate()
与一起使用str.maketrans()
:
trd = str.maketrans('()', '{}')
string1 = string1.translate(trd).format(**word_dict)
string2 = string2.translate(trd).format(**word_dict)
请记住,这将用大括号替换任何括号,即使它们没有包含要替换的单词也是如此。您可以rev_trd = str.maketrans('{}', '()')
在格式化字符串后使用来反向翻译其余的花括号;但通常到那时,最好还是使用for
循环,str.replace()
如第一部分代码所示。除非您可以将初始字符串更改为仅包含大括号,否则请使用该字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句