统计多个.txt文件词频:实现单词及出现次数展示(附代码)
Solution to Track Word Counts Per File
Hey there! I notice your current code calculates the total number of times each word appears across all your .txt files, but your goal is to show how many times each word shows up in individual files. Let's tweak the code to make that happen.
The Issue with Your Current Code
Your dictionary d only stores a single total count per word, which doesn't distinguish which file the word came from. We need to adjust the data structure to track counts per file.
Modified Code
listtxt = ['a.txt','b.txt','c.txt'] # Add your full list of files here output = open('dictionary.txt','w') # Use a nested dictionary: key = word, value = {filename: count} word_counts = {} for filename in listtxt: with open(filename,'r') as file: data = file.read() # Clean up punctuation and normalize to lowercase for char in '-.,;”“': data = data.replace(char,' ') data = data.lower() word_list = data.split() # Update counts for the current file for word in word_list: # Initialize the word's entry if it doesn't exist if word not in word_counts: word_counts[word] = {} # Increment count for this file (default to 0 if not present) word_counts[word][filename] = word_counts[word].get(filename, 0) + 1 # Write the results to the output file for word, file_counts in word_counts.items(): output.write(f"Word: *{word}*\n") for file, count in file_counts.items(): output.write(f" - {file}: {count} times\n") output.write("\n") # Add a blank line between words for readability output.close()
Key Changes Explained
- Nested Dictionary:
word_countsuses a dictionary inside a dictionary to map each word to its counts across different files. - Per-File Tracking: For each word, we now track how many times it appears in each file instead of just a total.
- Readable Output: The output file now clearly lists each word, followed by its occurrence count in every file it appears in.
Example Output in dictionary.txt
Word: *hello* - a.txt: 3 times - b.txt: 1 time Word: *world* - c.txt: 5 times
内容的提问来源于stack exchange,提问作者Martin Hoang
相关产品推荐
相关产品推荐

