如何用python计算段落中的句子数量

2024-06-20 15:11:03 发布

您现在位置:Python中文网/ 问答频道 /正文

这就是我目前所拥有的,但是我的pparagraph只包含5个句号,因此只有5个句子,但是它一直返回14个答案。有人能帮忙吗??

file = open ('words.txt', 'r')
lines= list (file)
file_contents = file.read()
print(lines)
file.close()
words_all = 0
for line in lines:
    words_all = words_all + len(line.split())
    print ('Total words:   ', words_all)
full_stops = 0
for stop in lines:
    full_stops = full_stops + len(stop.split('.'))
print ('total stops:    ', full_stops)

这是txt文件

盘车机是一种在磁带上操纵符号的装置 根据规则表。尽管图灵机很简单,但它可以 适合于模拟任何计算机算法的逻辑,尤其是 有助于解释计算机内部CPU的功能。“图灵” 机器在1936被艾伦图灵描述,他称之为 “a(自动)-机器”。图灵机并非实用的 计算技术,但作为一种假设的设备 计算机。图灵机器帮助计算机科学家理解 机械计算的极限。


Tags: intxtforlen计算机lineallfull
3条回答

最简单的方法是:

import nltk
nltk.download('punkt')
from nltk.tokenize import sent_tokenize

sentences = 'A Turning machine is a device that manipulates symbols on a strip of tape according to a table of rules. Despite its simplicity, a Turing machine can be adapted to simulate the logic of any computer algorithm, and is particularly useful in explaining the functions of a CPU inside a computer. The "Turing" machine was described by Alan Turing in 1936, who called it an "a(utomatic)-machine". The Turing machine is not intended as a practical computing technology, but rather as a hypothetical device representing a computing machine. Turing machines help computer scientists understand the limits of mechaniacl computation.'

number_of_sentences = sent_tokenize(sentences)

print(len(number_of_sentences))

输出:

5

使用正则表达式。

In [13]: import re
In [14]: par  = "This is a paragraph? So it is! Ok, there are 3 sentences."
In [15]: re.split(r'[.!?]+', par)
Out[15]: ['This is a paragraph', ' So it is', ' Ok, there are 3 sentences', '']

如果行不包含句点,split将返回单个元素:行本身:

>>> "asdasd".split('.')
    ['asdasd']

所以你要计算行数加上句号。你为什么要把文件分成几行?

with open('words.txt', 'r') as file:
    file_contents = file.read()

    print('Total words:   ', len(file_contents.split()))
    print('total stops:    ', file_contents.count('.'))

相关问题 更多 >