python-3.x 如何找到单词最长的一行?

mrphzbgm  于 2022-12-05  发布在  Python
关注(0)|答案(2)|浏览(165)

我需要从一个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))
bvjveswy

bvjveswy1#

与其他方法类似,但使用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
vfh0ocws

vfh0ocws2#

你可以用一个计数器来跟踪你在文件中遍历的行的行号。

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)

相关问题