【问题标题】:How do I stop regex from matching unwanted empty strings?如何阻止正则表达式匹配不需要的空字符串?
【发布时间】:2020-06-24 22:35:56
【问题描述】:

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

【问题讨论】:

    标签: python regex


    【解决方案1】:

    re.split 在这里工作正常。你在最后一个句子的末尾有一个!,所以它会在(一个句子)之前和之后(一个空字符)分割文本。

    您只需在行尾添加[:-1] 即可删除列表的最后一个元素:

    sentences = re.split(r"[.!?]+", intext)[:-1]
    

    输出:

    ['Congratulations', ' Today is your day', " You're off to Great Places", " You're off and away"]
    

    【讨论】:

      【解决方案2】:

      你可以使用理解:

      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()为什么返回一个空字符串,见this answer

      【讨论】:

      • 在这里使用推导很昂贵,它遍历所有列表只是为了删除最后一个元素。
      • @totok:不是真的,它可能是第一个元素、最后一个元素或介于两者之间的任何元素。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      相关资源
      最近更新 更多