簡體   English   中英

計算Python標點符號之間的單詞數

[英]Counting number of words between punctuation characters in Python

我想使用Python來計算文本輸入塊中某些標點符號之間出現的單詞數。 例如,對到目前為止編寫的所有內容的這種分析可以表示為:

[23,2,14]

...因為第一個句子除了結尾的句點外沒有其他標點符號,所以有23個單詞,接下來出現的“例如”短語有兩個單詞,其余以冒號結尾的單詞有14個單詞。

這樣做可能並不難,但是(與似乎沒有Pythonic的“不要重新發明輪子”哲學相伴隨)是否已經有特別適合該任務的內容?

punctuation_i_care_about="?.!"
split_by_punc =  re.split("[%s]"%punctuation_i_care_about, some_big_block_of_text)
words_by_puct = [len(x.split()) for x in split_by_punc]

Joran擊敗了我,但我將添加自己的方法:

from string import punctuation
import re

s = 'I want to use Python to count the numbers of words that occur between certain punctuation characters in a block of text input. For example, such an analysis of everything written up to this point might be represented as'

gen = (x.split() for x in re.split('[' + punctuation + ']',s))

list(map(len,gen))
Out[32]: [23, 2, 14]

(我愛map

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM