我想使用 Python 来计算文本输入块中某些标点字符之间出现的单词数。例如,对到目前为止所写的所有内容的这种分析可能表示为:
[23、2、14]
...因为第一个句子除了末尾的句号没有标点符号,有 23 个单词,接下来的“例如”短语有两个,其余以冒号结尾的短语有 14 个。
这可能不会太难做,但是(与似乎特别是 Pythonic 的“不要重新发明轮子”的理念相一致)是否已经有任何东西特别适合这项任务?
我想使用 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
)