I need to find the line, that contains the longest word from a txt file. I can find the longest word but I am not able to find in which line that word is. Here is the part of the code that works for me. I've tried a bunch of ways to find the line but I failed (I am a begginer at python).
def reading():
doc = open("C:/Users/s.txt", "r", encoding= 'utf-8')
docu = doc
return docu
def longest_word_place(document):
words = document.read().split()
i = 0
max = 0
max_place = 0
for i in range(len(words)):
if len(words[i]) > max:
max = len(words[i])
max_place = i
return max_place
document = reading()
print(longest_word_place(document))
CodePudding user response:
You can keep a counter that keeps track of the line number you're on as you iterate through the lines in the file. Something like:
with open('data.txt', 'r') as file:
lines = file.readlines()
counter = 0
max_length = 0
max_length_line = 0
for line in lines:
counter = 1
word_length = len(line)
if word_length > max_length:
max_length = word_length
max_length_line = counter
print(max_length, max_length_line)
CodePudding user response:
Similar to other approaches, but uses enumerate
as a line counter and checks each word (versus each line):
with open("phrases.txt", "r") as file:
lines = file.readlines()
max_word = ""
max_word_line = 0
for line_index, each_line in enumerate(lines, 1):
words_in_line = each_line.strip().split()
for each_word in words_in_line:
if len(each_word) > len(max_word):
max_word = each_word
max_word_line = line_index
print(f"{max_word = }, {max_word_line = }")
Output:
max_word = 'bandwidth-monitored', max_word_line = 55