如何统计文本文件每行非首单词数并输出单词最多行的首单词?
Solution for Tracking Line Word Counts (Excluding First Word)
Hey there! I see you've got a script that counts total words in your file, but let's tweak it to meet your actual goal: counting words excluding the first one per line, then outputting the first word from the line with the highest count of those words.
Let's break down what needs to change:
- Your current code sums all words across every line, but we need to track counts per line instead.
- We need to ignore the first word in each line when calculating the count.
- We need to keep track of which line has the highest count, and save its first word.
Here's the revised code:
# Initialize variables to track the maximum count and corresponding first word max_count = -1 result_first_word = "" # Use a 'with' statement to safely open/close the file (better practice than manual close) with open("C:/Users/John Green/Desktop/follows.txt", "r") as f: for line in f: # Split the line into a list of words (handles whitespace automatically) namelist = line.strip().split() # Skip empty lines to avoid index errors if not namelist: continue # Calculate number of words excluding the first one current_count = len(namelist) - 1 # Update our max tracking variables if current line has a higher count if current_count > max_count: max_count = current_count result_first_word = namelist[0] # Output the result print(f"The first word from the line with the most words (excluding itself) is: {result_first_word}")
Key improvements explained:
withstatement: Automatically closes the file even if an error occurs, which is more robust than manually callingf.close().strip(): Removes leading/trailing whitespace from each line, so empty lines (or lines with only spaces) are properly handled.- Empty line check: Skips lines with no words to prevent trying to access
namelist[0]on an empty list. - Tracking max count: We compare each line's count to our stored maximum, updating the result word whenever we find a higher count.
Edge cases to consider:
- If multiple lines have the same highest count, this code will return the first one encountered.
- Lines with only one word will have a count of 0, so they'll only be selected if all lines have 0 (or are empty).
内容的提问来源于stack exchange,提问作者johnson
相关产品推荐
相关产品推荐

