我希望计算每个句子的单词数,计算每个句子的平均单词,然后将该信息放入CSV文件中。到目前为止,这就是我所拥有的。我可能只需要知道在句点之前如何计算单词数即可。我也许可以从那里弄清楚。
#Read the data in the text file as a string
with open("PrideAndPrejudice.txt") as pride_file:
pnp = pride_file.read()
#Change '!' and '?' to '.'
for ch in ['!','?']:
if ch in pnp:
pnp = pnp.replace(ch,".")
#Remove period after Dr., Mr., Mrs. (choosing not to include etc. as that often ends a sentence although in can also be in the middle)
pnp = pnp.replace("Dr.","Dr")
pnp = pnp.replace("Mr.","Mr")
pnp = pnp.replace("Mrs.","Mrs")
要将字符串拆分为某个字符的字符串列表,请执行以下操作:
pnp = pnp.split('.')
然后,我们可以将每个句子拆分为一个字符串(单词)列表
pnp = [sentence.split() for sentence in pnp]
然后我们得到每个句子中的单词数
pnp = [len(sentence) for sentence in pnp]
然后我们可以使用statistics.mean
计算平均值:
statistics.mean(pnp)
要使用该文件,statistics
必须将其放在import statistics
文件的顶部。如果您不认识我的重新分配方式pnp
,请查看列表理解。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句