【问题标题】:Counting number of words between punctuation characters in Python计算Python中标点字符之间的单词数
【发布时间】:2014-01-18 19:49:41
【问题描述】:

我想使用 Python 计算文本输入块中某些标点字符之间出现的单词数。例如,对到目前为止所写的所有内容的这种分析可能表示为:

[23,2,14]

...因为第一个句子除了结尾的句号没有标点符号,有 23 个单词,接下来的“例如”短语有两个,其余以冒号结尾的短语有 14 个。

这可能不会太难做,但是(与“不要重新发明轮子”的哲学相一致,这似乎特别是 Pythonic)是否已经有任何东西特别适合这项任务?

【问题讨论】:

  • 另外,有任何你想解决的问题的真实例子吗?
  • 我尝试了一些随意的网络搜索(其中显示了很多用于词频计数的解析器等);也许这已经足够琐碎了,我自己写它的骨头毕竟不会有太大的麻烦。不过,以非专家的身份提问永远不会有什么坏处。至于问题,更像是一个实验。这只是其中的一小部分。

标签: python parsing text package text-analysis


【解决方案1】:
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]

【讨论】:

  • 您在“punctuation_i_care_about”中忘记了逗号。就目前而言,它不会输出操作正在寻找的内容。
  • Joran 的回答 = 举个例子,@geekazoid :-) Python 太棒了。
【解决方案2】:

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

【讨论】:

  • 我喜欢函数式编程;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多