Python实现列表元素排序及出现次数统计的代码问题求助
Fixing Your Word Frequency Counting Code
Let's break down what's going wrong with your code and fix it step by step—there are a few key issues that are preventing it from working as expected:
Key Problems in Your Original Code
- Treating a list like a dictionary: You initialized
wordas a list, but later tried to use string values (likecount) as indexes (word[count] = ...). Lists only accept integer indexes, so this will throw aTypeErrorimmediately. We need a dictionary to map words to their counts instead. - Indentation mistakes: The code under your
with openblock wasn't properly indented, which would cause logic errors when reading the file. - Inefficient and incorrect counting logic: Checking
if count in word(a list) doesn't track unique word counts—it just checks if the word exists anywhere in the list, and your loop would end up overcounting or failing entirely.
Corrected Code (Basic Version)
Here's a fixed version that follows your original intent and produces the output format you want:
# Initialize a dictionary to store word-to-count mappings word_counts = {} # Read and process the file line by line with open('Lateralus.txt', 'r') as my_file: for line in my_file: # Split each line into individual words words_in_line = line.split() for word in words_in_line: # Convert to lowercase to count "Above" and "above" as the same word lowercased_word = word.lower() # Update the count: increment if the word exists, set to 1 if it's new if lowercased_word in word_counts: word_counts[lowercased_word] += 1 else: word_counts[lowercased_word] = 1 # Sort the words alphabetically (optional, matches your sorted list intent) sorted_words = sorted(word_counts.items()) # Print in your desired format: "a 2 above 2 across 1..." for word, count in sorted_words: print(f"{word} {count}", end=' ') # Add a final newline for clean output print()
Simplified Version with collections.Counter
Python has a built-in tool for exactly this kind of counting task: Counter from the collections module. It simplifies the code significantly:
from collections import Counter word_counts = Counter() with open('Lateralus.txt', 'r') as my_file: for line in my_file: # Process each word, convert to lowercase, and update the counter for word in line.split(): word_counts[word.lower()] += 1 # Sort and print the results for word, count in sorted(word_counts.items()): print(f"{word} {count}", end=' ') print()
What This Fixes
- Uses a dictionary (or
Counter) to correctly track unique word counts instead of misusing a list. - Properly indents file-handling code to ensure all lines are processed.
- Handles case insensitivity by converting every word to lowercase.
- Produces the space-separated output format you requested: e.g.,
a 2 above 2 across 1 ...
内容的提问来源于stack exchange,提问作者Kimberly Sibal
相关产品推荐
相关产品推荐

