【问题标题】:How to count average word per sentence in python and saving by each article in a list?如何计算python中每个句子的平均单词并按列表中的每篇文章保存?
【发布时间】:2020-04-28 14:24:06
【问题描述】:

我在从数据框中计算每个句子的平均单词数时遇到问题。这就是我想做的事情

"On Saturday, September 17 at 8:30 pm EST, an explosion rocked West 23 Street in Manhattan, in the neighborhood commonly referred to as Chelsea, injuring 29 people, smashing windows and initiating street closures. There were no fatalities. Officials maintain that a homemade bomb, which had been placed in a dumpster, created the explosion.
2+6+8+8+3+6/6 = 5.6 for first sentence
4/1 = 4 for second sentence
6+7+3/3=5.1 for the third sentence

之后,我想保存列表中每篇文章中每个句子的平均单词。

非常感谢任何人的帮助,谢谢!

【问题讨论】:

  • 如何定义一个句子?我敢肯定我的定义和你的不一样。 :-)
  • 你如何定义一个词?我敢肯定我的定义和你的不一样。 :)
  • @erip 一个句子通过看句号来定义:")
  • @OliverMason 日期、数字、时间也字
  • 第二句有4个词,长度分别为5、4、2、10。所以4/4 = 1 for the second sentence似乎是错误的。你确定你的结果是正确的?

标签: python text nlp


【解决方案1】:

首先你会得到一个由.分隔的行列表

然后你得到由,分隔的短语

然后你得到每个短语中的单词,用space分隔

然后你得到每个单词的长度总和,然后除以总单词数

text = "On Saturday, September 17 at 8:30 pm EST, an explosion rocked West 23 Street in Manhattan, in the neighborhood commonly referred to as Chelsea, injuring 29 people, smashing windows and initiating street closures. There were no fatalities. Officials maintain that a homemade bomb, which had been placed in a dumpster, created the explosion."

lines = text.strip('.').split('.')
print("There are", len(lines), "lines present")

for line in lines:
    phrases = line.split(',')
    phrases = [phrase.strip() for phrase in phrases]
    words = [phrase.split() for phrase in phrases]
    lengths = [len(word) for word in words]
    print(f"{sum(lengths)}/{len(lengths)}={sum(lengths)/len(lengths)}") 

输出:

There are 3 lines present
33/6=5.5
4/1=4.0
16/3=5.333333333333333

【讨论】:

  • 似乎是什么问题?
  • 它不会产生 OP 发布的结果(因为它不捕获数字)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 2021-10-07
相关资源
最近更新 更多