How to select words of equal max length from a text document
<p>I am trying to write a program to read a text document and output the longest word in the document. If there are multiple longest words (i.e., all of equal length) then I need to output them all in the same order in which they occur. For example, if the longest words were dog and cat your code should produce:</p>

<p>dog cat</p>

<p>I am having trouble finding out how to select numerous words of equal max length and print them. This is as far as I've gotten, I am just struggling to think of how to select all words with equal max length:</p>

<p>open the file for reading</p>

<pre><code>fh = open('poem.txt', 'r')

longestlist = []  
longestword = ''  

for line in fh:
    words = (line.strip().split(' '))  
    for word in words:  
        word = ''.join(c for c in word if c.isalpha())  
        if len(word) &gt; (longestword):  
            longest.append(word)

for i in longestlist:  
    print i  
</code></pre>

<p>Ok, first off, you should probably use a <code>with</code> <code>as</code> statement, it just simplifies things and makes sure you don't mess up. So</p>

<p><code>fh = open('poem.txt', 'r')</code></p>

<p>becomes</p>

<p><code>with open('poem.txt','r') as file:</code></p>

<p>and since you're just concerned with words, you might as well use a built-in from the start:</p>

<pre><code>    words = file.read().split()
</code></pre>

<p>Then you just set a counter of the max word length (initialized to 0), and an empty list.  If the word has broken the max length, set a new maxlength and rewrite the list to include only that word.  If it's equal to the maxlength, include it in the list.  Then just print out the list members.  If you want to include some checks like <code>.isalpha()</code> feel free to put it in the relevant portions of the code.</p>

<pre><code>maxlength = 0
longestlist = []  
for word in words:
    if len(word) &gt; maxlength:
        maxlength = len(word)
        longestlist = [word]
    elif len(word) == maxlength:
        longestlist.append(word)
for item in longestlist:  
    print item
</code></pre>

<p>-MLP</p>

python string maxlength