Python技术求助:英文文本字母统计及柱状图绘制续接问题
Great start with fetching the text! Let's walk through the remaining steps to get your letter count and bar chart up and running. Here's how to build out the rest of your code:
Step 1: Read and Process the Fetched Text
First, you need to extract the text content from the HTTP response, then process each line to count letters. We'll ignore non-alphabetic characters and treat uppercase/lowercase letters the same for accurate counts.
import urllib.request import ssl from collections import defaultdict import matplotlib.pyplot as plt # Your existing SSL setup ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # Fetch the text (ensure your URL is fully valid!) response = urllib.request.urlopen('http://students.healthinformatics.uic.edu/~jlee118/551/text.txt', context=ctx) # Read and decode the response into a string, split into lines text_lines = response.read().decode('utf-8').splitlines() # Initialize a count dictionary (defaults to 0 for missing keys) letter_counts = defaultdict(int) # Process each line and count letters for line in text_lines: # Convert line to lowercase to make counting case-insensitive lower_line = line.lower() for char in lower_line: # Only count alphabetic characters if char.isalpha(): letter_counts[char] += 1 # Optional: Sort letters alphabetically for cleaner visualization sorted_letters = sorted(letter_counts.keys()) sorted_counts = [letter_counts[letter] for letter in sorted_letters]
Step 2: Create the Bar Chart with Matplotlib
Now that we have our counts, use matplotlib to visualize them as a bar chart. If you don't have matplotlib installed, run pip install matplotlib first.
# Set up the bar chart plt.figure(figsize=(12, 6)) plt.bar(sorted_letters, sorted_counts, color='skyblue') # Add labels and title for clarity plt.xlabel('Letters (A-Z)') plt.ylabel('Number of Occurrences') plt.title('Frequency of Each Letter in the Text') # Display the chart plt.show()
Key Tips:
- Case Insensitivity: Converting all characters to lowercase ensures 'A' and 'a' are counted together, which is standard for this type of analysis.
- Filtering Non-Letters: The
isalpha()check skips spaces, numbers, and punctuation so your counts only reflect actual letters. - Sorting: Sorting letters alphabetically makes the bar chart intuitive to read, following the familiar A-Z order.
- URL Validity: Double-check your URL is complete (the snippet you shared was cut off). Your SSL context setup should handle most untrusted certificates, but a broken URL will cause errors.
If you hit snags (like missing dependencies, invalid URLs, or unexpected counts), share more details and we can troubleshoot further!
内容的提问来源于stack exchange,提问作者Soha Sheikh

