我需要从一个txt文件中找到包含最长单词的那一行。我可以找到最长的单词,但是我找不到那个单词在哪一行。下面是适合我的部分代码。我尝试了很多方法来找到那一行,但是我失败了(我是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))
2条答案
按热度按时间bvjveswy1#
与其他方法类似,但使用
enumerate
作为行计数器并检查每个字(相对于每行):输出量:
vfh0ocws2#
你可以用一个计数器来跟踪你在文件中遍历的行的行号。