python - 如何阻止正则表达式匹配不需要的空字符串?
问题描述
我正在研究一个计算句子的问题。我决定通过使用正则表达式在字符“?,。,!”处拆分字符串来实现。当我将文本传递给 re.split 时,它在列表末尾包含一个空字符串。
源代码:
from cs50 import get_string
import re
def main():
text = get_string("Text: ")
cole_liau(text)
# Implement 0.0588 * L - 0.296 * S - 15.8; l = avg num of letters / 100 words , S = avg num of sentences / 100 words
def cole_liau(intext):
words = []
letters = []
sentences = re.split(r"[.!?]+", intext)
print(sentences)
print(len(sentences))
main()
输出:
文字:恭喜!今天是你的好日子。你要去伟大的地方!你已经离开了!
['Congratulations', ' Today is your day', " You're off to Great Places", " You're off and away", '']
5
我尝试添加 + 表达式以确保它至少匹配 1 [.!?] 但这也不起作用。
解决方案
您可以使用理解:
def cole_liau(intext):
words = []
letters = []
sentences = [sent for sent in re.split(r"[.!?]+", intext) if sent]
print(sentences)
print(len(sentences))
哪个产量
['Congratulations', ' Today is your day', " You're off to Great Places", " You're off and away"]
4
至于为什么re.split()
返回一个空字符串,请看这个答案。
推荐阅读
- console - radare2 和 AFL 使用哪个渲染引擎?
- python - 更改用户输入以从 python 中的命令行读取文件
- windows - Sublime Text 4 在文件保存时删除了 Ubuntu Terminal for Windows 的权限
- amazon-web-services - 为什么 AWS Lambda 函数非常适合 IOT 应用程序?
- java - 为什么 Map.entry::getKey 和 Map.entry::getValue 在流中对 hashmap 进行排序时不起作用?
- powershell - 对话 yammer 源 webpart 动态更新主题 ID(SharePoint 在线新式页面)
- javascript - 谷歌表格脚本代码根据具有任何值的行发送电子邮件(一次)
- python - 如何仅从时间戳中提取日期?
- windows-10 - PC 启动时浏览器中的“受 reCAPTCHA 保护”消息
- json - 为什么在 Flutter 的下一个屏幕上变量的值为 null?