Python Create List of Words Per Sentence and Calculate Mean and Place in CSV File
<p>I'm looking to count the number of words per sentence, calculate the mean words per sentence, and put that info into a CSV file. Here's what I have so far. I probably just need to know how to count the number of words before a period. I might be able to figure it out from there.</p>

<pre><code>#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")
</code></pre>

<p>To split a string into a list of strings on some character:</p>

<pre><code>pnp = pnp.split('.')
</code></pre>

<p>Then we can split each of those sentences into a list of strings (words)</p>

<pre><code>pnp = [sentence.split() for sentence in pnp]
</code></pre>

<p>Then we get the number of words in each sentence</p>

<pre><code>pnp = [len(sentence) for sentence in pnp]
</code></pre>

<p>Then we can use <code>statistics.mean</code> to calculate the mean:</p>

<pre><code>statistics.mean(pnp)
</code></pre>

<p>To use <code>statistics</code> you must put <code>import statistics</code> at the top of your file. If you don't recognize the ways I'm reassigning <code>pnp</code>, look up list comprehensions.</p>

python csv