J. Doe
J. Doe

Reputation: 338

Longest word in a txt file python code?

This is my version of this program. Is there a shorter and simpler way to do this?

d = open('txt.txt','r')
l = d.readlines()
string = l[0]
stringsplit = string.split()

d = []
for i in stringsplit:
    d.append(len(i))
    e = max(d)
for j in stringsplit:
    if len(j) == e:
        print("The longest word is", j, "and it is", len(j),"characters long")

Upvotes: 1

Views: 4297

Answers (2)

Timothy Murphy
Timothy Murphy

Reputation: 1362

You can use list comprehensions to turn the input into a single list and then use reduce on the resulting list to find the longest string.

f = open("input.txt", "r")
s = [y for x in f.readlines() for y in x.split()]
longest = reduce(lambda x, y: y if len(x) < len(y) else x, s, "")
print("The longest word is", longest, "and it is", len(longest),"characters long")

Upvotes: 1

zondo
zondo

Reputation: 20336

You can use the max() built-in function:

longest = max(stringsplit, key=len)
print("The longest word is {} and it is {} characters long".format(longest, len(longest)))

It is worth noting, however, that stringsplit is a list of the words in just the first line of the file, not the whole file itself. If you want it to be all of the words, use stringsplit = d.read().split()

Upvotes: 0

Related Questions