我有两个这样的字符串。
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()
,如第一个代码部分所示。除非您可以将初始字符串更改为仅包含大括号,否则请使用它。
关于python - 如何在 Python 字符串中替换括号和其中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32232005/