【频率分析法与Python程序代码实现(二):Matplotlib】

本文介绍了如何在Python中使用Matplotlib库进行数据可视化,包括风格设置、中文标签支持、负号显示,以及结合频率分析对英文文本进行字符统计。此外,还展示了如何对《独立宣言》的内容进行可视化展示。
摘要由CSDN通过智能技术生成
部分函数/方法
导入模块from pylab import *
风格设置plt.style
正常显示中文标签plt.rcParams[‘font.sans-serif’]
正常显示负号plt.rcParams[‘axes.unicode_minus’]
数据合法化list(),map()
绘图函数plt.bar()
标签plt.text()
图例plt.legend()
显示plt.show()

在这里插入图片描述

频率分析统计部分

dic = {chr(i+97):0 for i in range(26)}
def frequency_analysis(text):
    # 统计每个字符出现的频率
    # 大小写合并
    for char in text:
        if char in dic:
            dic[char] += 1
        elif char.lower() in dic:
            dic[char.lower()] += 1
            
    
    # 按照频率从高到低排序
    sorted_freq = sorted(dic.items(), key=lambda x: x[1], reverse=True)
    
    # 输出结果
    for item in sorted_freq:
        if item[1] != 0:
            print(item[0], ':', item[1])

text = input('input English text: ')
name = input('text name: ')

# 进行频率分析
frequency_analysis(text)

Matplotlib可视化部分

导入模块

from pylab import *

风格设置

plt.style.use('dark_background')

正常显示

plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

数据合法化

x1 = list(dic.keys())
x1 = list(map(str,x1))#使用list(map(str,x1))方法,将返回一个列表,列表中所有元素是str类型

y1 = list(dic.values())

绘图函数

plt.bar(x1,y1,label='text1')

数字标签

for a,b in zip(x1,y1):
    plt.text(a, b, 
             b, 
             ha='center', 
             va='bottom',
             fontsize=10,
             color='white',
             alpha=1
            )

图例、显示

plt.legend()
plt.show()

测试

:) 一个没有经过测试的程序是相对失败的

这回以独立宣言为文本进行测试:

The Declaration of Independence

When in the course of human events, it becomes necessary for one people todissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the laws Nature and Nature’s God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impelthem to the separation.
We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable rights, that they are among these are life, liberty and the pursuit of happiness. That to secure these rights, governments are instituted among them, deriving their just power from the consent of the governed. That whenever any form of government becomes destructive of these ends, it is the right of the people to alter or to abolish it, and to institute new government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their safety and happiness. Prudence, indeed, will dictate that governments long established should not be changed for light and transient causes; and accordingly all experience hath shown that mankind are more disposed to suffer, while evils are sufferable, than t right themselves by abolishing the forms to which they are accustomed. But when a long train of abuses and usurpations, pursuing invariably the same objectevinces a design to reduce them under absolute despotism, it is their right, it is their duty, to throw off such government, and to provide new guards for their future security. Such has been the patient sufferance of these Colonies; and such is now the necessity, which constrains them to alter their former systems of government. The history of the present King of Great Britain is usurpations, all having in direct object tyranny over these States. To prove this, let facts be submitted to a candid world.
He has forbidden his Governors to pass laws of immediate and pressing importance, unless suspended in their operation till his assent should be obtained; and when so suspended, he has utterly neglected to attend them.
He has refused to pass other laws for the accommodation of large districts of people, unless those people would relinquish the right of representation in the Legislature, a right inestimable to them and formidable to tyrants only.He has called together legislative bodies at places unusual, uncomfortable, and distant from the depository of their public records, for the sole purpose of fatiguing them into compliance with his measures.
He has dissolved representative houses repeatedly, for opposing with manly firmness his invasion on the rights of the people.
He has refused for a long time, after such dissolution, to cause others to be elected ; whereby the legislative powers, incapable of annihilation, have returned to the people at large for their exercise; the State remaining in the meantime exposed to all the dangers of invasion from without andconvulsion within.
He has endeavored to prevent the population of these states; for that purpose obstructing the laws of naturalizing of foreigners; refusing to pass others to encourage their migration hither, and raising the condition of new appropriations of lands.
He has obstructed the administration of justice, by refusing his assent of laws for establishing judiciary powers.
He has made judges dependent on his will alone, for the tenure of their office, and the amount and payment of their salary.
He has erected a multitude of new officers, and sent hither swarms of officers to harass our people, and eat out our substances.He has kept among us, in times of peace, standing armies without the consent of our legislatures.
He has affected to render the military independent of and superior to the civil power.He has combined with others to subject us to a jurisdiction foreign to our constitution, and unacknowledged by our laws; giving his assent to their acts of pretended legislation.For quartering large bodies of armed troops among us;
For protecting them, by a mock trial, from punishment for any murder which they should commit on the inhabitants of these States.
For cutting off our trade with all parts of the world;For imposing taxes on us without our consent;
For depriving us in many cases, of the benefits of trial by jury;
For transporting us beyond seas to be tried for pretended offenses;
For abolishing the free systems of English laws in a neighboring Province, establishing therein an arbitrary government, and enlarging its boundaries so as to render it at once an example and fit instrument for introducing the same absolute rule these Colonies;
For taking away our Charters, abolishing our most valuable laws, and alteringfundamentally the forms of our governments;
For suspending our own Legislatures, and declaring themselves invested with power to legislate for us in all cases whatsoever.
He has abdicated government here, by declaring us out of his protection and waging war against us.He has plundered our seas, ravaged our coasts, burnt our towns, and destroyed the lives of our people.
He is at this time transporting large armies of foreign mercenaries to complete the works of death, desolation and tyranny, already begun with circumstances of cruelty and perfidy scarcely parallel in the most barbarousages, and totally unworthy the head of a civilized nation.
He has constrained our fellow citizens taken captive on the high seas to bear arms against their country, to become the executioners of their friends and brethren, or to fall themselves by their hands.
He has excited domestic insurrection amongst us, and has endeavored to bring on the inhabitants of our frontiers, the merciless Indian savages, whose known rule of warfare, is an undistinguished destruction of all ages, sexes, and conditions.In every stage of these oppressions we have petitioned for redress in the most humble terms: our repeated petition have been answered only by repeated injury. A prince whose character is thus marked by every act which may define a tyrant is unfit to be the ruler of a free people.
Nor have we been wanting in attention to our British brethren. We have warned them from time to time of attempts by their legislature to extend an unwarrantable jurisdiction over us. We have reminded them of the circumstances of our emigration and settlement here. We have appealed to their native justice and magnanimity, and we have conjured them by the ties of our common kindred to disavow these usurpation, which would inevitably interrupt our connections and correspondence. They too have been deaf to the voice of justice and of consanguinity. We must, therefore, acquiesce in the necessity, which denounces our separation, and hold them., as we hold the rest of mankind, enemies in war, in peace friends.
We, therefore, the Representatives of the United States of America, in General Congress assembled , appealing to the supreme Judge of the world for the rectitude of our intentions, do, in the name, and by authority of the good people of these Colonies, solemnly publish and declare, That these United States Colonies and Independent States; that they are absolved by from all allegiance to the British Crown, and that all political connection between them and the State, they have full power to levy war, conclude peace, contract alliances, establish commerce, and to do all other acts and things which Independent States may of right do. And for the support of this declaration, with a firm reliance on the protection of Divine Providence, we mutually pledge to each other our lives, our fortunes, and our sacred honor.

在这里插入图片描述

在这里插入图片描述

  • 50
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值