2013-03-05 228 views
1

這是迄今爲止我所知道的,但是我的pparagraph只包含5個句號,因此只有5個句子。但它一直保持返回14作爲答案。誰能幫忙?如何計算python中段落中句子的數量

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的功能的 。 1933年,Alan Turing對「圖靈」機器進行了描述,他稱之爲「一種(自動)機器」。圖靈機並不是作爲一種實用的計算技術,而是作爲代表計算機的虛擬設備。圖靈機幫助計算機科學家理解機械計算的極限。

+1

您正在計算零件*之間*滿座。爲什麼不使用'stop.count('。')'而不是? – 2013-03-05 15:46:18

+0

你可以發佈words.txt內容嗎? – drekyn 2013-03-05 15:46:22

+0

@MartijnPieters不僅是時段之間的分段,還有換行符和句點之間的分段。 – 2013-03-05 15:47:24

回答

3

如果某行不包含期間,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('.')) 
+0

非常感謝你:-) – 2013-03-05 15:54:02

0

嘗試

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

詳情:

with open("words.txt") as f: 
    data = f.read() 
    print "total stops: ", data.count(".") 
+0

也有'file_contents'變量.. – 2013-03-05 15:48:34

+0

@MartijnPieters謝謝,更新... – ATOzTOA 2013-03-05 15:49:14

+0

在OPs代碼中'file_contents'是空的,該文件已經通過迭代在'list'內讀取。 – 2013-03-05 15:49:44

1

使用正則表達式。

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', '']