CQM*_*CQM 247 python text replace
我想使用.replace函数来替换多个字符串.
我现在有
string.replace("condition1", "")
Run Code Online (Sandbox Code Playgroud)
但是想要有类似的东西
string.replace("condition1", "").replace("condition2", "text")
Run Code Online (Sandbox Code Playgroud)
虽然那感觉不是很好的语法
这样做的正确方法是什么?有点像grep/regex你可以做什么\1
,\2
并将字段替换为某些搜索字符串
And*_*ark 242
这是一个简短的例子,应该使用正则表达式:
import re
rep = {"condition1": "", "condition2": "text"} # define desired replacements here
# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
#Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest versions
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
Run Code Online (Sandbox Code Playgroud)
例如:
>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")
'() and --text--'
Run Code Online (Sandbox Code Playgroud)
Jos*_*sen 117
你可以做一个很好的小循环功能.
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
Run Code Online (Sandbox Code Playgroud)
text
完整字符串在哪里,dic
是一个字典 - 每个定义都是一个字符串,它将替换该术语的匹配.
注意:在Python 3中,iteritems()
已被替换为items()
小心: Python字典没有可靠的迭代顺序.此解决方案仅解决您的问题,如果:
例如:
d = { "cat": "dog", "dog": "pig"}
mySentence = "This is my cat and this is my dog."
replace_all(mySentence, d)
print(mySentence)
Run Code Online (Sandbox Code Playgroud)
可能的输出#1:
"This is my pig and this is my pig."
可能的输出#2
"This is my dog and this is my pig."
一种可能的解决方法是使用OrderedDict.
from collections import OrderedDict
def replace_all(text, dic):
for i, j in dic.items():
text = text.replace(i, j)
return text
od = OrderedDict([("cat", "dog"), ("dog", "pig")])
mySentence = "This is my cat and this is my dog."
replace_all(mySentence, od)
print(mySentence)
Run Code Online (Sandbox Code Playgroud)
输出:
"This is my pig and this is my pig."
Run Code Online (Sandbox Code Playgroud)
小心#2:如果你的text
字符串太大或字典中有很多对,效率低下.
Bjö*_*ist 88
以下是使用reduce的第一个解决方案的变体,以备您正常使用.:)
repls = {'hello' : 'goodbye', 'world' : 'earth'}
s = 'hello, world'
reduce(lambda a, kv: a.replace(*kv), repls.iteritems(), s)
Run Code Online (Sandbox Code Playgroud)
martineau甚至更好的版本:
repls = ('hello', 'goodbye'), ('world', 'earth')
s = 'hello, world'
reduce(lambda a, kv: a.replace(*kv), repls, s)
Run Code Online (Sandbox Code Playgroud)
小智 85
为什么不这样的解决方案呢?
s = "The quick brown fox jumps over the lazy dog"
for r in (("brown", "red"), ("lazy", "quick")):
s = s.replace(*r)
#output will be: The quick red fox jumps over the quick dog
Run Code Online (Sandbox Code Playgroud)
mmj*_*mmj 33
这只是对FJ和MiniQuark的一个更简洁的回顾.您需要实现多个同时串替换的功能如下:
def multiple_replace(string, rep_dict):
pattern = re.compile("|".join([re.escape(k) for k in sorted(rep_dict,key=len,reverse=True)]), flags=re.DOTALL)
return pattern.sub(lambda x: rep_dict[x.group(0)], string)
Run Code Online (Sandbox Code Playgroud)
用法:
>>>multiple_replace("Do you like cafe? No, I prefer tea.", {'cafe':'tea', 'tea':'cafe', 'like':'prefer'})
'Do you prefer tea? No, I prefer cafe.'
Run Code Online (Sandbox Code Playgroud)
如果您愿意,您可以从这个更简单的更换功能开始.
Min*_*ark 28
我根据FJ的优秀答案建立了这个:
import re
def multiple_replacer(*key_values):
replace_dict = dict(key_values)
replacement_function = lambda match: replace_dict[match.group(0)]
pattern = re.compile("|".join([re.escape(k) for k, v in key_values]), re.M)
return lambda string: pattern.sub(replacement_function, string)
def multiple_replace(string, *key_values):
return multiple_replacer(*key_values)(string)
Run Code Online (Sandbox Code Playgroud)
一次性用法:
>>> replacements = (u"café", u"tea"), (u"tea", u"café"), (u"like", u"love")
>>> print multiple_replace(u"Do you like café? No, I prefer tea.", *replacements)
Do you love tea? No, I prefer café.
Run Code Online (Sandbox Code Playgroud)
请注意,由于替换仅在一次通过中完成,"café"更改为"tea",但它不会更改回"café".
如果您需要多次进行相同的更换,您可以轻松创建替换功能:
>>> my_escaper = multiple_replacer(('"','\\"'), ('\t', '\\t'))
>>> many_many_strings = (u'This text will be escaped by "my_escaper"',
u'Does this work?\tYes it does',
u'And can we span\nmultiple lines?\t"Yes\twe\tcan!"')
>>> for line in many_many_strings:
... print my_escaper(line)
...
This text will be escaped by \"my_escaper\"
Does this work?\tYes it does
And can we span
multiple lines?\t\"Yes\twe\tcan!\"
Run Code Online (Sandbox Code Playgroud)
改进:
请享用!:-)
Fre*_*ihl 20
我想提出字符串模板的用法.只需将要替换的字符串放在字典中即可完成所有设置!来自docs.python.org的示例
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
[...]
ValueError: Invalid placeholder in string: line 1, col 10
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
[...]
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
Run Code Online (Sandbox Code Playgroud)
Jam*_*oss 14
在我的情况下,我需要用名称简单替换唯一键,所以我想到了这一点:
a = 'This is a test string.'
b = {'i': 'I', 's': 'S'}
for x,y in b.items():
a = a.replace(x, y)
>>> a
'ThIS IS a teSt StrIng.'
Run Code Online (Sandbox Code Playgroud)
Xav*_*hot 10
从开始Python 3.8
,并引入赋值表达式(PEP 572)(:=
运算符),我们可以在列表推导中应用替换项:
# text = "The quick brown fox jumps over the lazy dog"
# replacements = [("brown", "red"), ("lazy", "quick")]
[text := text.replace(a, b) for a, b in replacements]
# text = 'The quick red fox jumps over the quick dog'
Run Code Online (Sandbox Code Playgroud)
我的0.02美元.它基于Andrew Clark的答案,只是更清楚一点,它还涵盖了当要替换的字符串是要替换的另一个字符串的子字符串(更长的字符串获胜)的情况
def multireplace(string, replacements):
"""
Given a string and a replacement map, it returns the replaced string.
:param str string: string to execute replacements on
:param dict replacements: replacement dictionary {value to find: value to replace}
:rtype: str
"""
# Place longer ones first to keep shorter substrings from matching
# where the longer ones should take place
# For instance given the replacements {'ab': 'AB', 'abc': 'ABC'} against
# the string 'hey abc', it should produce 'hey ABC' and not 'hey ABc'
substrs = sorted(replacements, key=len, reverse=True)
# Create a big OR regex that matches any of the substrings to replace
regexp = re.compile('|'.join(map(re.escape, substrs)))
# For each match, look up the new string in the replacements
return regexp.sub(lambda match: replacements[match.group(0)], string)
Run Code Online (Sandbox Code Playgroud)
正是在这个要点中,如果您有任何建议,请随时修改它.
小智 7
我需要一个解决方案,其中要替换的字符串可以是正则表达式,例如,通过用单个字符替换多个空白字符来帮助规范化长文本.基于其他人的一系列答案,包括MiniQuark和mmj,这就是我想出的:
def multiple_replace(string, reps, re_flags = 0):
""" Transforms string, replacing keys from re_str_dict with values.
reps: dictionary, or list of key-value pairs (to enforce ordering;
earlier items have higher priority).
Keys are used as regular expressions.
re_flags: interpretation of regular expressions, such as re.DOTALL
"""
if isinstance(reps, dict):
reps = reps.items()
pattern = re.compile("|".join("(?P<_%d>%s)" % (i, re_str[0])
for i, re_str in enumerate(reps)),
re_flags)
return pattern.sub(lambda x: reps[int(x.lastgroup[1:])][1], string)
Run Code Online (Sandbox Code Playgroud)
它适用于其他答案中给出的示例,例如:
>>> multiple_replace("(condition1) and --condition2--",
... {"condition1": "", "condition2": "text"})
'() and --text--'
>>> multiple_replace('hello, world', {'hello' : 'goodbye', 'world' : 'earth'})
'goodbye, earth'
>>> multiple_replace("Do you like cafe? No, I prefer tea.",
... {'cafe': 'tea', 'tea': 'cafe', 'like': 'prefer'})
'Do you prefer tea? No, I prefer cafe.'
Run Code Online (Sandbox Code Playgroud)
对我来说最重要的是你也可以使用正则表达式,例如仅替换整个单词,或者规范化空格:
>>> s = "I don't want to change this name:\n Philip II of Spain"
>>> re_str_dict = {r'\bI\b': 'You', r'[\n\t ]+': ' '}
>>> multiple_replace(s, re_str_dict)
"You don't want to change this name: Philip II of Spain"
Run Code Online (Sandbox Code Playgroud)
如果要将字典键用作普通字符串,则可以在使用例如此函数调用multiple_replace之前将其转义:
def escape_keys(d):
""" transform dictionary d by applying re.escape to the keys """
return dict((re.escape(k), v) for k, v in d.items())
>>> multiple_replace(s, escape_keys(re_str_dict))
"I don't want to change this name:\n Philip II of Spain"
Run Code Online (Sandbox Code Playgroud)
以下函数可以帮助您在字典键中查找错误的正则表达式(因为来自multiple_replace的错误消息不是很有说服力):
def check_re_list(re_list):
""" Checks if each regular expression in list is well-formed. """
for i, e in enumerate(re_list):
try:
re.compile(e)
except (TypeError, re.error):
print("Invalid regular expression string "
"at position {}: '{}'".format(i, e))
>>> check_re_list(re_str_dict.keys())
Run Code Online (Sandbox Code Playgroud)
请注意,它不会链接替换,而是同时执行它们.这样可以在不限制其功能的情况下提高效率.要模仿链接的效果,您可能只需要添加更多字符串替换对并确保对的预期排序:
>>> multiple_replace("button", {"but": "mut", "mutton": "lamb"})
'mutton'
>>> multiple_replace("button", [("button", "lamb"),
... ("but", "mut"), ("mutton", "lamb")])
'lamb'
Run Code Online (Sandbox Code Playgroud)
这是一个在具有许多小替换的长字符串上更有效的示例。
source = "Here is foo, it does moo!"
replacements = {
'is': 'was', # replace 'is' with 'was'
'does': 'did',
'!': '?'
}
def replace(source, replacements):
finder = re.compile("|".join(re.escape(k) for k in replacements.keys())) # matches every string we want replaced
result = []
pos = 0
while True:
match = finder.search(source, pos)
if match:
# cut off the part up until match
result.append(source[pos : match.start()])
# cut off the matched part and replace it in place
result.append(replacements[source[match.start() : match.end()]])
pos = match.end()
else:
# the rest after the last match
result.append(source[pos:])
break
return "".join(result)
print replace(source, replacements)
Run Code Online (Sandbox Code Playgroud)
重点是避免长字符串的多次串联。我们将源字符串切成片段,在形成列表时替换一些片段,然后将整个字符串重新连接回字符串。
小智 5
我在一份学校作业中做了类似的练习。这是我的解决方案
dictionary = {1: ['hate', 'love'],
2: ['salad', 'burger'],
3: ['vegetables', 'pizza']}
def normalize(text):
for i in dictionary:
text = text.replace(dictionary[i][0], dictionary[i][1])
return text
Run Code Online (Sandbox Code Playgroud)
自己在测试字符串上查看结果
string_to_change = 'I hate salad and vegetables'
print(normalize(string_to_change))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
333716 次 |
最近记录: |