1

I want to count the number of words in each line of a text file (not including the first word) and then print the first word of the line with the most words in it?

At the moment I'm only able to count the number of words in the entire text file.

f = open("C:/Users/John Green/Desktop/follows.txt", "r")
for line in f:
   namelist = line.split()
   names += len(namelist)
f.close()
print(names)
johnson
  • 11
  • 3
  • A similar question was posted. You can get answer from here https://stackoverflow.com/questions/34057328/counting-words-per-line-from-text-file-in-python – Nirav Patel May 23 '18 at 00:29

2 Answers2

0

You can use a `list' and make a list of list. I would make a main list to store a index and then attach the list returned from "split()" ( ["word1","wordN"] ).

So you can simply print the first item of the list where the max_index points to.

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
poooool
  • 1
  • 2
0

Your line variable is not a line, but is all of the text. Try giving the split function a new line argument '\n' to get a list of the lines. Also your for loop for reading the file was not necessary.

def count_words(line):
    words = line.split()
    return len(words)

f = open("C:/Users/John Green/Desktop/follows.txt", "r")
text = f.read()
#make a list of the file broken into lines
lines = text.split('\n')
max_words = -1
word = ''
for line in lines:
    length = count_words(line)
    if length > max_words:
        max_words = length
        words = line.split()
f.close()
print(words[0])
Andrew T
  • 184
  • 1
  • 7
  • Hi thanks, I put this code in and it's only giving me the first word on the first line which is not the first word of the line with the most words in it. can you explain further? where you said "make a list of the file broken into lines" do you want me to literally make a list into my code cause if so the file contains 459186 words. – johnson May 23 '18 at 01:14
  • Sorry, I just updated the code and got rid of a bug. The comment is referring to the following line. "text.split('\n')" returns a list full of lines. The rest of the code is finding the maximum word count by going through each line and replacing the "words" variable each time a larger line is found. – Andrew T May 23 '18 at 01:28