python - 有没有办法替换和删除多行字符串的行
问题描述
我正在尝试处理多行字符串,替换和删除一些行。这是代码。
>>> txt
'1 Introduction\nPart I: Applied Math and Machine Learning Basics\n2 Linear Algebra'
>>> tmp = []
>>> for line in txt.splitlines():
... if re.findall('[0-9]', line):
... replaced = re.sub('[0-9]', '#', line)
... tmp.append(replaced)
>>> print(tmp)
['# Introduction', '# Linear Algebra']
这段代码虽然完成了我的工作,但我不确定它是否是最有效的方法。
有没有更有效的方法来做到这一点?
解决方案
您可以对问题中提供的代码使用列表推导,这使代码整洁。
[re.sub('[0-9]', '#', line) for line in txt.splitlines() if re.findall('[0-9]', line) ]
# Output
['# Introduction', '# Linear Algebra']
此外,就像@CertainPerformance 在评论中提到的那样,因为您只想知道字符串中是否存在数字,所以最好使用search
而不是findall
. 然后您可以将列表理解代码重写为,
[re.sub('[0-9]', '#', line) for line in txt.splitlines() if re.search('[0-9]', line) ]
# Output
['# Introduction', '# Linear Algebra']
search
在我的机器上使用时,我可以看到一个小的性能改进。
%%timeit 1000000
[re.sub('[0-9]', '#', line) for line in txt.splitlines() if re.search('[0-9]', line) ]
# 4.76 µs ± 53.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit 1000000
[re.sub('[0-9]', '#', line) for line in txt.splitlines() if re.findall('[0-9]', line) ]
# 5.21 µs ± 114 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
推荐阅读
- java - Classpath problems while Instrumenting Springboot application
- c++ - 如果'C'从'B'公开继承,B从'A'私下继承,为什么我不能在'C'内部创建'A'的对象?
- ios - 如何在 iOS 上使用 Swift 将 10 多个 RSS Feed 解析并组合成一个数组
- azure - azure-webapp-maven-plugin 在将 maven 应用程序部署到 azure 服务器时发生错误“非套接字上的套接字操作:configureBlocking”
- node.js - nodejs 将两个视频连接在一起?
- android - 确定一个矩形是否适合另一个
- javascript - 在单击功能上从 vue js 减少 MongoDb 列中的数字
- python - pandas concat() 不在同一列上加入
- forms - 如何在 vueJS 中删除输入焦点上的错误提示
- sql - 群组分析