我试图制作一个简单的脚本来替换文本中出现的某些组或字符集(或字符串集)
在本例中,我将尝试用特定字符串替换所有字母“a、e、I、o、u”
我的剧本:
def replace_all(text, repl):
text1 = text.replace("a", repl)
text2 = text1.replace("e", repl)
text3 = text2.replace("i", repl)
text4 = text3.replace("o", repl)
text5 = text4.replace("u", repl)
return text5
有没有更简单的方法?如果我需要替换更大的字符或字符串组,该怎么办?像这样把它拴起来似乎并没有什么效果
这可能是一个原始的问题。然而,我仍处于学习阶段,所以我可能会在以后的课程中得到它。提前感谢您的建议
这是一个非常适合regular expression的地方:
这将适用于您问题中替换单个字符的情况。如果要替换一组较长的字符串,请执行以下操作:
据我所知,有
3
种不同的方法可以做到这一点,所有这些方法都比您的方法短:for-loop
generator-comprehension
regular expressions
首先,使用
for-loop
。这可能是对代码最直接的改进,本质上只是将5
行减少到2
:您还可以使用
generator-comprehension
和str.join
方法在一行中完成。这会更快(如果这很重要的话),因为它很复杂O(n)
,因为我们将遍历每个字符并对其进行一次计算(第一种方法是complexityO(n^5)
,因为Python将针对不同的替换循环五次text
)因此,这种方法很简单:
最后,我们可以使用^{} 将集合中的所有字符
[aeiou]
替换为文本repl
。这是最短的解决方案,我可能会推荐:正如我在开始时所说的,所有这些方法都完成了任务,因此我没有必要提供单独的测试用例,但它们确实可以工作,如本测试中所示:
更新
我注意到了一种新方法:
str.translate
这种方法也是{},因此与前两种方法一样有效
所以你所做的是完全正确的,但是有更好的方法
下面是一些解决方案,运行时占用了100000个循环
主签名:
目标是要替换的字符,repl是替换字符
Bytearray
Bytearray是一个可变的数据结构,包含字符本身的列表。作为一种数据结构,它似乎是一种理想的选择,python中的字符串是不可变的,这可以避免不断的构造/破坏
运行速度为0.365
无bytearray
这在一个简单的列表上操作,列表本身是可变的,但是字符是字符串,因此这里对技术上不可变的结构进行了一些修改
以0.179的速度运行
地图
这将函数映射到字符串中的每个字符
以0.265的速度运行
相关问题 更多 >
编程相关推荐