1

这是我到目前为止所拥有的,但我的段落只包含 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 年描述,他称其为“自动(自动)机器”。图灵机并非旨在作为一种实用的计算技术,而是作为一种代表计算机的假设设备。图灵机帮助计算机科学家了解机械计算的局限性。

4

4 回答 4

6

使用正则表达式。

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', '']
于 2013-03-05T15:52:57.950 回答
6

如果一行不包含句点,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('.'))
于 2013-03-05T15:48:41.050 回答
6

最简单的方法是:

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
于 2018-11-07T18:17:38.520 回答
0

尝试

print "total stops: ", open('words.txt', 'r').read().count(".")

细节:

with open("words.txt") as f:
    data = f.read()
    print "total stops: ", data.count(".")
于 2013-03-05T15:47:58.717 回答