You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python技术求助:英文文本字母统计及柱状图绘制续接问题

Completing Your Letter Count & Bar Chart Project

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:12:02