Longest word in a txt file python code? - python

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")

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")

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()

Related

Python - Finding the longest word in a text file error

I am trying to find the longest word in a text file and it keeps on saying:
ValueError: max() arg is an empty sequence
def find_longest_word(filename):
with open(filename,'r+') as f:
words = f.read().split()
max_len_word = max(words,key=len)
print('maximum length word in file :',max_len_word)
print('length is : ',max_len_word)
print(find_longest_word('data1.txt'))
What did I do wrong?
This should work for you:
from functools import reduce
def find_longest_word(filename):
f = open(filename, "r")
s = [y for x in f.readlines() for y in x.split()]
longest_word = reduce(lambda x, y: y if len(x) < len(y) else x, s, "")
print("The longest word is", longest_word, "and it is", len(longest_word),"characters long")
return longest_word
print(find_longest_word('input.txt'))
I have tested the code inside the function and it works but without the function declaration.
I see that your code is missing indentation on line 2. Also, you want to print a return value from the function but your function does not return anything. So maybe your code should be like this.
def find_longest_word(filename):
with open(filename,'r+') as f:
words = f.read().split()
max_len_word = max(words,key=len)
max_len = len(max(words,key=len))
return max_len_word, max_len
And the usage of the function should be like this.
word, length = find_longest_word('data1.txt')
print("max length word in file: ", word)
print("length is: ", length)

How to find the some word in the text file

I have a file text, I want filter some word in the text with condition:
1) same the length and starting with same a letter
2) find words with the at least 2 correctly placed letters
For example:
word = bubal
text
byres
brits
blurb
bulks
bible
debug
debut
and want to output: ['bulks', 'bible'] with bulks have 'b' and 'u' correctly placed and bible have 2 b correctly placed with bubal
My ideal to find the word with starting a lettre and so find the word same length and then find the word correct 2nd condition
But I write the code find the word starting by using re and it don't run good
import re
with open('words.txt','r') as file:
liste = file.read()
word = re.findall('[b]\w+',liste)
print(word)
My code return the ['byres','brits','bulks','but','bug']
How to fix it and find word flows condition
Edited based on your comment.
This may be what you're after:
#!/usr/bin/env python
def find_best_letter_matches(lines, target):
m = []
m_count = 0
for line in lines:
count = sum(map(lambda x: x[0] == x[1], zip(line, target)))
if count > m_count:
m = []
m_count = count
if count == m_count:
m.append(line)
return m
def find_n_letter_matches(lines, target, n):
m = []
for line in lines:
count = sum(map(lambda x: x[0] == x[1], zip(line, target)))
if count >= n:
m.append(line)
return m
if __name__ == '__main__':
with open('text.txt', 'r') as f:
lines = f.read().split('\n')
best_matches = find_best_letter_matches(lines, 'bubal')
n_matches = find_n_letter_matches(lines, 'bubal', 2)
print('Best letter matches', best_matches)
print('At least 2 letters match', n_matches)
The functions compare each line to the target, letter by letter, and counts the number of matches. The first then returns the list of the highest matching lines, and the second returns all that match with n or more letters.
The output with your example text (with bubal added) is:
Best letter matches ['bubal']
At least 2 letters match ['bulks', 'bible', 'bubal']
Try this
wordToSearch = "bubal"
singlesChar = list(wordToSearch)
finalArray = []
with open('words.txt','r') as file:
liste = file.readlines()
for each in liste:
each = each.rstrip()
fn = list(each)
flag = 0
for i in range(0,len(singlesChar)):
if(fn[i] == singlesChar[i]):
flag+=1
if(flag >= 2): finalArray.append(each)
print(finalArray)

Finding a longest string in for loop

I have the task to write a program in which the user inputs 8 words, after which the program prints the longest word inputed and counts the length of the word. I'm having problems with finding the longest inputed string. Here's my code:
counter = 0
for i in range(8):
x = str(input('Enter a word: '))
counter = len(x)
if counter == max(counter):
print('The longest word is: ', counter)
which of course doesn't work.
max can take an argument key which is applied to each element:
words = [raw_input('Enter a word: ') for _ in xrange(8)]
max_word = max(words, key=len)
This ought to do it - this sorts the list using the 'len' operator to obtain the length of each string, and [-1] just picks the last (the longest) one.
words = []
for i in range(8):
words.append(raw_input('Enter a word: '))
longestWord = sorted(words, key=len)[-1]
print 'The longest word is %s (%s character%s)' % (longestWord, len(longestWord), len(longestWord) != 1 and 's' or '')
Mind you it is somewhat inefficient in that it stores all inputs in the array until the loop is over. Maybe better would be this:
longestWord = ''
for i in range(8):
word = raw_input('Enter a word: ')
if len(word) > len(longestWord):
longestWord = word
print 'The longest word is %s (%s character%s)' % (longestWord, len(longestWord), len(longestWord) != 1 and 's' or '')
Consider keeping the lengths in a list and finding the max value in that list.
counter=""
for i in range(8):
x=str(input('Enter a word: '))
if len(counter) < len(x):
counter = x
print('The longest word is: ',x)

Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n

Whenever I run this code it just gives me a blank list, I am wondering what I am doing wrong. I am trying to print a list of words that are longer than n. When i try to run the updated code it only prints the first word from the list of words that i enter.
def filterlongword(string,number):
for i in range(len(string)):
listwords = []
if len(string[i]) > number:
listwords.append(string[i])
return listwords
def main():
words = input("Please input the list of words: ")
integer = eval(input("Please input an integer: "))
words1 = filterlongword(words,integer)
print("The list of words greater than the integer is",words1)
main()
Initialize listwords before the loop
Return listwords after the loop
Split the input string into a list of words
def filterlongword(string,number):
listwords = []
for i in range(len(string)):
if len(string[i]) > number:
listwords.append(string[i])
return listwords
And a nicer version using list comprehension:
def filterlongword(string,number):
return [word for word in string if len(word) > number]
To split the input string into a list of words, use
words = input("Please input the list of words: ").split()
even better would be just
def filterlongword(string,number):
return filter(lambda word:len(word)>number, string)
# or: return [w for w in string if len(w) > number]
def listing(guess, number):
new_list = []
for i in range(len(guess)):
if len(guess[i]) > number:
new_list.append(guess[i])
print (new_list)
list1 = input("take input: ")
list = list1.split(",")
def main():
global list, integer1
integer = input()
integer1 = int(integer)
listing(list, integer1)
main()
**try this code..this will work, use a delimiter to form a list of your input **
Your main problem is passing words as a single string rather than an iterable of strings. The secondary problem is not specifying the separator between words for the missing .split. Here is my version.
I made longwords a generator function because in actually use, one does not necessary need the sequence of long words to be a list, and I gave an example of this in the output formatting.
def longwords(wordlist, length):
return (word for word in wordlist if len(word) >= length)
def main():
words = input("Enter words, separated by spaces: ").split()
length = int(input("Minimum length of words to keep: "))
print("Words longer than {} are {}.".format(length,
', '.join(longwords(words, length))))
main()
This results in, for instance
Enter words, separated by spaces: a bb ccc dd eeee f ggggg
Minimum length of words to keep: 3
Words longer than 3 are ccc, eeee, ggggg.
Maybe you can shorten the code to the following:
def filter_long_words():
n = raw_input("Give words and a number: ").split()
return sorted(n)[1:] # sorted the List , number it is the shorter .
# called the item from the second position to ende .
print filter_long_words()
def filter_long_words(**words**,**number**):
l=[]
split = **words**.split(",")
for i in split:
if len(i) > **number**:
l.append(i)
return l
**w** = input("enter word:")
**n** = int(input("Enter number"))
filter_long_words(**w**,**n**)
TRY THIS
***
def filter_long_words(n, words):
list_of_words=[]
a= words.split(" ")
for x in a:
if len(x)>n:
list_of_words.append(x)
return list_of_words
for i in range(len(listOfWords)):
listOfInt = []
for i in range(len(listOfWords)):
listOfInt.append(len(listOfWords[i]))
print('List of word length: ',listOfInt)
def filter_long_words(lst,n):
a=[]
for i in lst:
if n<len(i):
a.append(i)
return a
To filter list of words
def filter_long_words(lst,n):
return [word for word in lst if len(word)>n]

Write a function that takes a list of words and returns the longest word and length of the longest one

The full question is "Write a function find_longest_word() that takes a list of words and
returns the longest word and length of the longest one. You should also write a test function
that will request the users for a list of words and print the longest word and its length."
I wrote this code and it works. I just need to figure out how i can add a function into this code to to what I am told in the question.
def main():
text = input("Please input a list of words to evaluate: ")
longest = 0
for words in text.split():
if len(words) > longest:
longest = len(words)
longest_word = words
print("The longest word is", longest_word, "with length", len(longest_word))
main()
Simply move the logic, into a function, like this
def find_longest_word(text):
for words in text.split():
if len(words) > longest:
longest = len(words)
longest_word = words
return longest_word, len(longest_word)
def main():
input_string = input("Please input a list of words to evaluate: ")
longest_word = find_longest_word(input_string)
print("The longest word is", longest_word, "with length", len(longest_word))
The actual problem, you are trying to solve can be solved like this
def find_longest_word(text):
longest_word = max(text.split(), key = len)
return longest_word, len(longest_word)
Note: Instead of printing the result in the find_longest_word function, we are returning the longest_word from it, so that the function does only what it is supposed to do. Now, as the name suggests, it just finds the longest word.
This exercise with a short codec....
def main():
a = sorted(input("Please input a list of words to evaluate: ").split(), key=len) [-1]
print ("You longe word ", str(a), " have this", str(len(a)), "lenghts")
main()
You do not need longest_word = words, but without your answer, It was not possible to answer this exercise ...., so thanks!
def main ():
text = input("Please input a List of words to evaluate: ")
longest = 0
for words in text.split():
if len(words) > longest:
longest = len(words)
print ("The longest word is", words, "with lenght", longest)
main()
def find_longest_word(words_list):
word_len = []
for n in words_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][1]
print(find_longest_word(["hasta ", "lavista", "baby"]))
this is a python program to read a list of words and return the length of the longest one:
list_words = ["PHP", "Exercises", "Backend"]<br/>
s = [(len(word),word) for word in list_words] <br/>
s.sort() <br/>
print('Longest String in list is ',s[-1][1]) <br/>
numberOfWordsInList = int(input("Enter number of words to be List: "))
def longestWordInList(numberOfWordsInListt):
createdList = [input("Enter any word: ") for i in range(numberOfWordsInList)]
lengthOfItems = [(len(items), items) for items in createdList]
return max(lengthOfItems)
print(longestWordInList(numberOfWordsInList))

Categories