如何找到单词最长的一行?



我需要找到文本文件中包含最长单词的行。我能找到最长的单词,但我找不到这个单词在哪一行。这是对我有用的部分代码。我尝试了很多方法来找到这一行,但我失败了(我是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))

与其他方法类似,但使用enumerate作为行计数器并检查每个单词(相对于每行):

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

输出:

max_word = 'bandwidth-monitored', max_word_line = 55

可以保留一个计数器,在遍历文件中的行时跟踪所处的行号。比如:


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)

最新更新