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

Python字符与标点频率图表无法显示,新手寻求技术帮助

Hey there! Let's figure out why your character and punctuation frequency plots are showing up blank in Spyder while your word frequency ones work. I took a look at your code and spotted a few key issues that are probably causing this.

First: Fix Your File Handling in the __init__ Method

Right now, your AnalysisVisualiser class's __init__ function accepts df1 to df6 parameters but never uses them. Worse, you're just opening files without reading their content—if your tokenise method expects text data instead of an open file handle, it's working with empty input, which leads to empty frequency stats and blank plots.

Fix it by reading the file content properly (using with statements also ensures files get closed safely):

def __init__(self):
    # Read each file's content into a string variable
    with open('Richard_II_Shakespeare.tok', 'r', encoding='utf-8') as f:
        self.df_rich = f.read()
    with open('Edward_II_Marlowe.tok', 'r', encoding='utf-8') as f:
        self.df_Edw = f.read()
    with open('Hamlet_Shakespeare.tok', 'r', encoding='utf-8') as f:
        self.df_ham = f.read()
    with open('Henry_VI_Part1_Shakespeare.tok', 'r', encoding='utf-8') as f:
        self.df_hen1 = f.read()
    with open('Henry_VI_Part2_Shakespeare.tok', 'r', encoding='utf-8') as f:
        self.df_hen2 = f.read()
    with open('Jew_of_Malta_Marlowe.tok', 'r', encoding='utf-8') as f:
        self.df_jew = f.read()

Second: Verify Your Data at Each Step

Blank plots almost always mean you're trying to plot empty data. Add print statements to check if your token lists and frequency stats are actually populated:

  • In visualise_character_frequency, after getting token1, add:
    print("First 10 tokens from Richard II:", token1[:10])
    print("Character frequency stats for Richard II:", ac1)
    
  • In visualise_punctuation_frequency, after getting pun1, add:
    print("Punctuation frequency stats for Richard II:", pun1)
    

If these print empty lists or dictionaries, you'll need to check your preprocessor_StudentID.py (make sure tokenise correctly splits text into tokens) and character_Student.py (ensure analyse_characters and get_punctuation_frequency are counting properly—for punctuation, confirm it's checking against something like string.punctuation).

Third: Clean Up Redundant Code (And Fix Plot Logic)

Your visualise_punctuation_frequency method creates WordAnalyser instances that you never use—delete those lines. Also, you're fetching token1 to token6 twice, which is unnecessary.

Plus, line plots (plt.plot) aren't great for discrete data like character/punctuation frequencies. Switch to bar plots for better readability, and use subplots to avoid overlapping lines from 6 different texts:
For character frequency:

# Create a grid of subplots
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
axes = axes.flatten()

# Pair each dataset with its title and subplot axis
text_data = [
    (ac1, 'Richard II', axes[0]),
    (ac2, 'Edward II', axes[1]),
    (ac3, 'Hamlet', axes[2]),
    (ac4, 'Henry VI Part 1', axes[3]),
    (ac5, 'Henry VI Part 2', axes[4]),
    (ac6, 'Jew of Malta', axes[5])
]

# Plot each text's character frequency
for freq_dict, title, ax in text_data:
    ax.bar(freq_dict['val'], freq_dict['frq'])
    ax.set_title(title)
    ax.tick_params(axis='x', rotation=45)  # Rotate labels to avoid overlap

plt.tight_layout()
plt.suptitle('Character Frequency Across Elizabethan Texts', y=1.02)
plt.show()

Do the same adjustment for your punctuation frequency plot using plt.bar instead of plt.plot.

Quick Recap of the Fix Flow

  1. Fix file reading to pass actual text content to your tokeniser
  2. Print intermediate data to confirm tokens and frequency stats exist
  3. Adjust your plots to use bar charts for discrete character/punctuation data
  4. Clean up unused code to avoid confusion

Once you fix the file reading and confirm your frequency stats have data, your plots should stop showing up blank!

内容的提问来源于stack exchange,提问作者user9669809

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:07:06