Python 如何考虑省略号的出现来计算句子
我编写了以下脚本来计算文本文件中的句子数:Python 如何考虑省略号的出现来计算句子,python,regex,Python,Regex,我编写了以下脚本来计算文本文件中的句子数: import re filepath = 'sample_text_with_ellipsis.txt' with open(filepath, 'r') as f: read_data = f.read() sentences = re.split(r'[.{1}!?]+', read_data.replace('\n','')) sentences = sentences[:-1] sentence_count = len(sente
import re
filepath = 'sample_text_with_ellipsis.txt'
with open(filepath, 'r') as f:
read_data = f.read()
sentences = re.split(r'[.{1}!?]+', read_data.replace('\n',''))
sentences = sentences[:-1]
sentence_count = len(sentences)
但是,如果我在包含以下内容的sample\u text\u上运行它,则使用_ellipsis.txt
:
Wait for it... awesome!
我得到的是语句\u count=2
而不是1
,因为它不会忽略省略号(即“…”)
我在正则表达式中尝试的是通过
{1}
使它只匹配一个句点的一次出现,但这显然不是我想要的方式。如何让正则表达式忽略省略号?用这样的正则表达式拆分句子是不够的。请参阅了解如何利用NLTK实现这一点
回答你的问题,你称3点序列为省略号。因此,您需要使用
[!?]+|(?<!\.)\.(?!\.)
用这样的正则表达式拆分句子是不够的。请参阅了解如何利用NLTK实现这一点 回答你的问题,你称3点序列为省略号。因此,您需要使用
[!?]+|(?<!\.)\.(?!\.)
根据Wiktor关于使用NLTK的建议,我还提出了以下替代解决方案:
import nltk
read_data="Wait for it... awesome!"
sentence_count = len(nltk.tokenize.sent_tokenize(read_data))
这将产生预期的1个句子计数。根据Wiktor关于使用NLTK的建议,我还提出了以下替代解决方案:
import nltk
read_data="Wait for it... awesome!"
sentence_count = len(nltk.tokenize.sent_tokenize(read_data))
这将产生预期的句子计数1。是
等待它。。。太棒了代码>被认为是一句话还是两句话?re.split(r')(?是等它…太棒了!
被认为是一句话还是两句话?re.split(r')(?