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>You can try the code below.</p>

<pre><code>numbers_per_sentence =  [len(element) for element in (element.split() for element in pnp.split("."))]
mean = sum(numbers_per_sentence)/len(numbers_per_sentence)
</code></pre>

<p>However, for real natural language processing I would probably recommend a more robust solution such as <a href="http://www.nltk.org/" rel="nofollow">NLTK</a>. The text manipulation you perform (replacing "?" and "!", removing commas after "Dr.","Mr." and "Mrs.") is probably not enough to be 100% sure that comma is always a sentence separator (and that there are no other sentence separators in your text, even if it happens to be true for Pride And Prejudice)</p>

python csv