首页 > 解决方案 > 文本文件中每行的总字数

问题描述

我想计算文本文件每行中的单词数(不包括第一个单词),然后打印其中单词最多的行的第一个单词?

目前我只能计算整个文本文件中的单词数。

f = open("C:/Users/John Green/Desktop/follows.txt", "r")
for line in f:
   namelist = line.split()
   names += len(namelist)
f.close()
print(names)

标签: python-3.x

解决方案


您可以使用“列表”并制作列表列表。我会创建一个主列表来存储索引,然后附加从“split()”([“word1”,“wordN”])返回的列表。

因此,您可以简单地打印 max_index 指向的列表的第一项。

f = open("C:/Users/John Green/Desktop/follows.txt", "r")

word_list = []
max_index = 0
max_num_word = 0

for index,line in enumerate(f.readlines(),0):
    namelist = line.split()
    word_list[index].append(namelist) # adding the new list
    if (max_num_word < len(namelist)):
        max_num_word = len(namelist)
        max_index = index

f.close() 
print namelist[max_index][0] #first word of the most num words line

推荐阅读