How to count the number of words in a paragraph and exclude some words (from file)?
Question: I've just started to learn Python so my question might be a bit silly. I'm
trying to create a program that would:  
\- import a text file (got it)  
\- count the total number of words (got it),  
\- count the number of words in a specific paragraph, starting with a specific
phrase (e.g. "P1", ending with another participant "P2") and exclude these
words from my word count. Somehow I ended up with something that counts the
number of characters instead :/  
\- print paragraphs separately (got it)  
\- exclude "P1" "P2" etc. words from my word count.

My text files look like that:  
P1: Bla bla bla.  
P2: Bla bla bla bla.  
P1: Bla bla.  
P3: Bla.

I ended up with this code:

    
    
    text = open (r'C:/data.txt', 'r')
    lines = list(text)
    text.close()
    words_all = 0
    for line in lines:
        words_all = words_all + len(line.split())
    print 'Total words:   ', words_all
    
    words_par = 0
    for words_par in lines:
        if words_par.startswith("P1" or "P2" or "P3") & words_par.endswith("P1" or "P2" or "P3"):
            words_par = line.split()
        print len(words_par)
        print words_par.replace('P1', '') #doesn't display it but still counts
    else:
        print 'No words'
    

Any ideas how to improve it?

Thanks


Answer: You shouldn't call `open ('zery.txt', 'r')` with identifier **text**. It is
not the text in the file, it is the handler of the file, described as a "file-
like object" in the docs (I never understood what it means, "file-like
object", by the way)

.

    
    
    with open ('C:/data.txt', 'r')  as f:
        ........
        ........
    

is better than

    
    
    f = open ('C:/data.txt', 'r') 
        ......
        .....
    f.close()
    

.

You should read the instructions concerning **split()** , so you'll see that
you can do:

    
    
    with open ('C:/data.txt', 'r') as f:
        text = f.read()
    words_all = len(text.split())
    print 'Total words:   ', words_all
    

.

If the structure of your text is:

    
    
    P1: Bla bla bla. 
    P2: Bla bla bla bla. 
    P1: Bla bla. 
    P3: Bla.
    

then `words_par.endswith("P1" or "P2" or "P3")` is always _False_ , hence the
desired spliting isn't performed.

Consequently, **words_par** doesn't become a list, it remains a string, that's
why the characters are counted.

.

Also, your code is certainly wrong.

If the splitting was performed, it would be the last **line** obtained in the
first for-loop, in the beginning of the code, that would be repeatedly
splitted.

So, instead of

    
    
    for words_par in lines: 
        if words_par.startswith("P1" or "P2" or "P3"):
            words_par = line.split() 
    

it is certainly:

    
    
    for line in lines: 
        if line[0:2] in ("P1","P2","P3") :
            words_par = line.split() 
    

