首页 > 解决方案 > 如何阻止正则表达式匹配不需要的空字符串?

问题描述

我正在研究一个计算句子的问题。我决定通过使用正则表达式在字符“?,。,!”处拆分字符串来实现。当我将文本传递给 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 [.!?] 但这也不起作用。

标签: pythonregex

解决方案


您可以使用理解:

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()返回一个空字符串,请看这个答案


推荐阅读