Python 有没有更好的方法来计算句子中的标点符号?

Python 有没有更好的方法来计算句子中的标点符号?,python,counting,punctuation,Python,Counting,Punctuation,我想数一数“结束句”,例如句号、感叹号和问号 我写了一个小循环来实现这一点,但我想知道是否有更好的方法。不允许使用内置函数 for line in textContent: numberOfFullStops += line.count(".") numberOfQuestionMarks += line.count("?") numberOfQuestionMarks += line.count("!") numberOfSentences = numberOfFul

我想数一数“结束句”,例如句号、感叹号和问号

我写了一个小循环来实现这一点,但我想知道是否有更好的方法。不允许使用内置函数

for line in textContent:
    numberOfFullStops += line.count(".")
    numberOfQuestionMarks += line.count("?")
    numberOfQuestionMarks += line.count("!")

numberOfSentences = numberOfFullStops + numberOfQuestionMarks + numberOfExclamationMarks
假设您想在一个句子中计算结束标点,我们可以通过循环每个字符串的字符并过滤标点来生成(字符,计数)对的字典

演示

以下是三个自上而下提供的中级到初级数据结构选项:

import collections as ct


sentence = "Here is a sentence, and it has some exclamations!!"
terminals = ".?!"

# Option 1 - Counter and Dictionary Comprehension
cd = {c:val for c, val in ct.Counter(sentence).items() if c in terminals}
cd
# Out: {'!': 2}


# Option 2 - Default Dictionary
dd = ct.defaultdict(int)
for c in sentence:
    if c in terminals:
        dd[c] += 1
dd
# Out: defaultdict(int, {'!': 2})


# Option 3 - Regular Dictionary
d = {}
for c in sentence:
    if c in terminals:
        if c not in d:
            d[c] = 0
        d[c] += 1
d
# Out: {'!': 2}
要进一步扩展,对于单独的
句子列表
,请循环后面的选项之一

for sentence in sentences:
    # add option here
注:若要对每个句子的标点符号总数进行求和,请对
dict.values()
进行求和,例如
sum(cd.values())


更新:假设您要按句号点字法拆分句子,请使用正则表达式:

import re


line = "Here is a string of sentences.  How do we split them up?  Try regular expressions!!!"


# Option - Regular Expression and List Comprehension
pattern = r"[.?!]"
sentences = [sentence for sentence in re.split(pattern, line) if sentence]
sentences
# Out: ['Here is a string of sentences', '  How do we split them up', '  Try regular expressions']

len(sentences)
# Out: 3
注意,
有5个终端,但只有3个句子。因此,正则表达式是一种更可靠的方法

参考资料


您需要为它们单独计数吗?这里的目的是什么——数数标点符号还是数数句子的数量?“因为这不是5句话!!!”这里什么算是“内置函数”?您能使用标准库模块吗?对不起。我指的是方法。举个例子,如果有什么东西可以自动剥离它,那么我们就不允许使用它。例如,如果我们在排序,我们就不允许使用variable.sort(),但你可以使用
.count
?@JonClements我需要看看找到了多少个句子。谢谢你。:-)帮了大忙,没问题。我已经根据你的评论更新了这篇文章,希望更接近你想要的。此外,随着答案不断被公布,不要忘记对那些你认为有用的答案进行投票,并接受最终的解决方案。