词云可视化可以说是基本上所有做文本分析相关任务的同学都不陌生的东西了,市面上也有几款不错的词云可视化模块,我用的最多的还是大名鼎鼎的wodcloud,相信绝大多数的人用的也是这一款词云可视化模块,官方仓库地址在这里,首页截图如下所示:

逼近1w的star量,足可见其受欢迎程度之深了。

今天我要介绍的是另一款更有趣更具个性化的词云宝库stylecloud,它是基于wordcloud开发的上层应用,源码也是只有不到300行,主要是好玩有趣,官方地址在这里,首页截图如下所示:

作者给出来的使用方法也是很简单的,这里我迫不及待想要实践尝试一下了。首先看下效果:

stylecloud的核心源码如下:

from icon_font_to_png.icon_font import IconFont
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import csv
import os
from PIL import Image
from matplotlib.colors import to_rgb
import numpy as np
import fire
from shutil import rmtree
from pkg_resources import resource_filename
from typing import List, UnionSTATIC_PATH = resource_filename(__name__, "static")def file_to_text(file_path: str):"""Reads a text file, or if the file is a .csv,read as a dict of word/weights."""if not file_path.endswith(".csv"):with open(file_path, "r", encoding="utf-8") as f:text = f.read()return textelse:  # parse as a CSVwith open(file_path, "r", encoding="utf-8") as f:r = csv.reader(f)header = next(r)assert len(header) <= 2, "The input CSV has too many columns."# If a single-column CSV, read as a bulk textif len(header) == 1:texts = ""for row in r:texts += row[0] + "\n"# If a two-column CSV, read as words/weightselif len(header) == 2:texts = {}for row in r:texts[row[0]] = float(row[1])return textsdef gen_fa_mask(icon_name: str = "fas fa-grin",size: int = 512,icon_dir: str = ".temp",pro_icon_path: str = None,pro_css_path: str = None,
):"""Generates a Font Awesome icon mask from the given FA prefix + name."""# FA prefixes which map to a font file.font_files = {"fas": "fa-solid-900.ttf","far": "fa-regular-400.ttf","fab": "fa-brands-400.ttf",}icon_prefix = icon_name.split(" ")[0]icon_name_raw = icon_name.split(" ")[1]css_path = pro_css_path or os.path.join(STATIC_PATH, "fontawesome.min.css")ttf_path = pro_icon_path or os.path.join(STATIC_PATH, font_files[icon_prefix])icon = IconFont(css_file=css_path, ttf_file=ttf_path)# If a length and width are provided, make icon the smaller of the twoif isinstance(size, tuple):size = min(size)icon.export_icon(icon=icon_name_raw[len(icon.common_prefix) :],size=size,filename="icon.png",export_dir=icon_dir,)def gen_palette(palette: str):"""Generates the corresponding palette function from `palettable`."""palette_split = palette.split(".")palette_name = palette_split[-1]# https://stackoverflow.com/a/6677505palette_func = getattr(__import__("palettable.{}".format(".".join(palette_split[:-1])),fromlist=[palette_name],),palette_name,)return palette_funcdef gen_mask_array(icon_dir: str, invert_mask: bool, size: int):"""Generates a numpy array of an icon mask."""icon = Image.open(os.path.join(icon_dir, "icon.png"))if isinstance(size, int):size = (size, size)# https://stackoverflow.com/a/2563883icon_w, icon_h = icon.sizeicon_mask = Image.new("RGBA", icon.size, (255, 255, 255, 255))icon_mask.paste(icon, icon)mask = Image.new("RGBA", size, (255, 255, 255, 255))mask_w, mask_h = mask.sizeoffset = ((mask_w - icon_w) // 2, (mask_h - icon_h) // 2)mask.paste(icon_mask, offset)mask_array = np.array(mask, dtype="uint8")if invert_mask:mask_array = np.invert(mask_array)return mask_arraydef gen_gradient_mask(size: int,palette: str,icon_dir: str = ".temp",gradient_dir: str = "horizontal",invert_mask: bool = False,
):"""Generates a gradient color mask from a specified palette."""mask_array = gen_mask_array(icon_dir, invert_mask, size)mask_array = np.float32(mask_array)palette_func = gen_palette(palette)gradient = palette_func.mpl_colormap(np.linspace(0.0, 1.0, size))# matplotlib color maps are from range of (0, 1). Convert to RGB.gradient *= 255.0# Add new axis and repeat gradient across it.gradient = np.tile(gradient, (size, 1, 1))# if vertical, transpose the gradient.if gradient_dir == "vertical":gradient = np.transpose(gradient, (1, 0, 2))# Turn any nonwhite pixels on the icon into the gradient colors.white = (255.0, 255.0, 255.0, 255.0)mask_array[mask_array != white] = gradient[mask_array != white]image_colors = ImageColorGenerator(mask_array)return image_colors, np.uint8(mask_array)def color_to_rgb(color):"""Converts a color to a RGB tuple from (0-255)."""if isinstance(color, tuple):# if a RGB tuple alreadyreturn colorelse:# to_rgb() returns colors from (0-1)color = tuple(int(x * 255) for x in to_rgb(color))return colordef gen_stylecloud(text: str = None,file_path: str = None,size: int = 512,icon_name: str = "fas fa-flag",palette: str = "cartocolors.qualitative.Bold_5",colors: Union[str, List[str]] = None,background_color: str = "white",max_font_size: int = 200,max_words: int = 2000,stopwords: bool = True,custom_stopwords: Union[List[str], set] = STOPWORDS,add_stopwords: bool = False,icon_dir: str = ".temp",output_name: str = "stylecloud.png",gradient: str = None,font_path: str = os.path.join(STATIC_PATH, "Staatliches-Regular.ttf"),random_state: int = None,collocations: bool = True,invert_mask: bool = False,pro_icon_path: str = None,pro_css_path: str = None,
):"""Generates a stylecloud!:param text: Input text. Best used if calling the function directly.:param file_path: File path of the input text/CSV. Best used on the CLI.:param size: Size (length and width in pixels) of the stylecloud.:param icon_name: Icon Name for the stylecloud shape. (e.g. 'fas fa-grin'):param palette: Color palette (via palettable):param colors: Custom color(s) for text (name or hex). Overrides palette.:param background_color: Background color (name or hex).:param max_font_size: Maximum font size in the stylecloud.:param max_words: Maximum number of words to include in the stylecloud.:param stopwords: Boolean to filter out common stopwords.:param custom_stopwords: list of custom stopwords.:param add_stopwords: Whether to use custom_stopwords to add to default:param icon_dir: Temp directory to store the icon mask image.:param output_name: Output file name of the stylecloud.:param gradient: Direction of gradient. (if not None, will use gradient):param font_path: Path to .ttf file for font to use in stylecloud.:param random_state: Controls random state of words and colors.:param collocations: Whether to include collocations (bigrams) of two words.:param invert_mask: Whether to invert the icon mask.:param pro_icon_path: Path to Font Awesome Pro .ttf file if using FA Pro.:param pro_css_path: Path to Font Awesome Pro .css file if using FA Pro."""assert any([text, file_path]), "Either text or file_path must be specified."if file_path:text = file_to_text(file_path)gen_fa_mask(icon_name, size, icon_dir, pro_icon_path, pro_css_path)if gradient and colors is None:pal_colors, mask_array = gen_gradient_mask(size, palette, icon_dir, gradient, invert_mask)else:  # Color each word randomly from the palettemask_array = gen_mask_array(icon_dir, invert_mask, size)if colors:# if specifying a single color stringif isinstance(colors, str):colors = [colors]# iterate through each color to ensure correct RGB format.# see matplotlib docs on how colors are decoded:# https://matplotlib.org/3.1.1/api/colors_api.htmlcolors = [color_to_rgb(color) for color in colors]else:palette_func = gen_palette(palette)colors = palette_func.colorsdef pal_colors(word, font_size, position, orientation, random_state, **kwargs):rand_color = np.random.randint(0, len(colors))return tuple(colors[rand_color])if add_stopwords:custom_stopwords.extend(STOPWORDS)# cleanup icon folderrmtree(icon_dir)wc = WordCloud(background_color=background_color,font_path=font_path,max_words=max_words,mask=mask_array,stopwords=custom_stopwords if stopwords else None,max_font_size=max_font_size,random_state=random_state,collocations=collocations,)# generate word cloudif isinstance(text, str):wc.generate_from_text(text)else:  # i.e. a dict of word:value from a CSVif stopwords:  # manually remove stopwords since otherwise ignoredtext = {k: v for k, v in text.items() if k not in custom_stopwords}wc.generate_from_frequencies(text)wc.recolor(color_func=pal_colors, random_state=random_state)wc.to_file(output_name)def stylecloud_cli(**kwargs):"""Entrypoint for the stylecloud CLI."""fire.Fire(gen_stylecloud)

不难看出是gen_stylecloud函数真正的核心方法,如下所示:

按照官方的样例,这里我用的数据集是constitution.txt,如下:

We the People of the United States, in Order to form a more perfect Union, establish Justice, insure domestic Tranquility, provide for the common defence, promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the United States of America.Article. I.Section. 1.All legislative Powers herein granted shall be vested in a Congress of the United States, which shall consist of a Senate and House of Representatives.Section. 2.The House of Representatives shall be composed of Members chosen every second Year by the People of the several States, and the Electors in each State shall have the Qualifications requisite for Electors of the most numerous Branch of the State Legislature.No Person shall be a Representative who shall not have attained to the Age of twenty five Years, and been seven Years a Citizen of the United States, and who shall not, when elected, be an Inhabitant of that State in which he shall be chosen.Representatives and direct Taxes shall be apportioned among the several States which may be included within this Union, according to their respective Numbers, which shall be determined by adding to the whole Number of free Persons, including those bound to Service for a Term of Years, and excluding Indians not taxed, three fifths of all other Persons. The actual Enumeration shall be made within three Years after the first Meeting of the Congress of the United States, and within every subsequent Term of ten Years, in such Manner as they shall by Law direct. The Number of Representatives shall not exceed one for every thirty Thousand, but each State shall have at Least one Representative; and until such enumeration shall be made, the State of New Hampshire shall be entitled to chuse three, Massachusetts eight, Rhode-Island and Providence Plantations one, Connecticut five, New-York six, New Jersey four, Pennsylvania eight, Delaware one, Maryland six, Virginia ten, North Carolina five, South Carolina five, and Georgia three.When vacancies happen in the Representation from any State, the Executive Authority thereof shall issue Writs of Election to fill such Vacancies.The House of Representatives shall chuse their Speaker and other Officers; and shall have the sole Power of Impeachment.Section. 3.The Senate of the United States shall be composed of two Senators from each State, chosen by the Legislature thereof for six Years; and each Senator shall have one Vote.Immediately after they shall be assembled in Consequence of the first Election, they shall be divided as equally as may be into three Classes. The Seats of the Senators of the first Class shall be vacated at the Expiration of the second Year, of the second Class at the Expiration of the fourth Year, and of the third Class at the Expiration of the sixth Year, so that one third may be chosen every second Year; and if Vacancies happen by Resignation, or otherwise, during the Recess of the Legislature of any State, the Executive thereof may make temporary Appointments until the next Meeting of the Legislature, which shall then fill such Vacancies.No Person shall be a Senator who shall not have attained to the Age of thirty Years, and been nine Years a Citizen of the United States, and who shall not, when elected, be an Inhabitant of that State for which he shall be chosen.The Vice President of the United States shall be President of the Senate, but shall have no Vote, unless they be equally divided.The Senate shall chuse their other Officers, and also a President pro tempore, in the Absence of the Vice President, or when he shall exercise the Office of President of the United States.The Senate shall have the sole Power to try all Impeachments. When sitting for that Purpose, they shall be on Oath or Affirmation. When the President of the United States is tried, the Chief Justice shall preside: And no Person shall be convicted without the Concurrence of two thirds of the Members present.Judgment in Cases of Impeachment shall not extend further than to removal from Office, and disqualification to hold and enjoy any Office of honor, Trust or Profit under the United States: but the Party convicted shall nevertheless be liable and subject to Indictment, Trial, Judgment and Punishment, according to Law.Section. 4.The Times, Places and Manner of holding Elections for Senators and Representatives, shall be prescribed in each State by the Legislature thereof; but the Congress may at any time by Law make or alter such Regulations, except as to the Places of chusing Senators.The Congress shall assemble at least once in every Year, and such Meeting shall be on the first Monday in December, unless they shall by Law appoint a different Day.Section. 5.Each House shall be the Judge of the Elections, Returns and Qualifications of its own Members, and a Majority of each shall constitute a Quorum to do Business; but a smaller Number may adjourn from day to day, and may be authorized to compel the Attendance of absent Members, in such Manner, and under such Penalties as each House may provide.Each House may determine the Rules of its Proceedings, punish its Members for disorderly Behaviour, and, with the Concurrence of two thirds, expel a Member.Each House shall keep a Journal of its Proceedings, and from time to time publish the same, excepting such Parts as may in their Judgment require Secrecy; and the Yeas and Nays of the Members of either House on any question shall, at the Desire of one fifth of those Present, be entered on the Journal.Neither House, during the Session of Congress, shall, without the Consent of the other, adjourn for more than three days, nor to any other Place than that in which the two Houses shall be sitting.Section. 6.The Senators and Representatives shall receive a Compensation for their Services, to be ascertained by Law, and paid out of the Treasury of the United States. They shall in all Cases, except Treason, Felony and Breach of the Peace, be privileged from Arrest during their Attendance at the Session of their respective Houses, and in going to and returning from the same; and for any Speech or Debate in either House, they shall not be questioned in any other Place.No Senator or Representative shall, during the Time for which he was elected, be appointed to any civil Office under the Authority of the United States, which shall have been created, or the Emoluments whereof shall have been encreased during such time; and no Person holding any Office under the United States, shall be a Member of either House during his Continuance in Office.Section. 7.All Bills for raising Revenue shall originate in the House of Representatives; but the Senate may propose or concur with Amendments as on other Bills.Every Bill which shall have passed the House of Representatives and the Senate, shall, before it become a Law, be presented to the President of the United States: If he approve he shall sign it, but if not he shall return it, with his Objections to that House in which it shall have originated, who shall enter the Objections at large on their Journal, and proceed to reconsider it. If after such Reconsideration two thirds of that House shall agree to pass the Bill, it shall be sent, together with the Objections, to the other House, by which it shall likewise be reconsidered, and if approved by two thirds of that House, it shall become a Law. But in all such Cases the Votes of both Houses shall be determined by yeas and Nays, and the Names of the Persons voting for and against the Bill shall be entered on the Journal of each House respectively. If any Bill shall not be returned by the President within ten Days (Sundays excepted) after it shall have been presented to him, the Same shall be a Law, in like Manner as if he had signed it, unless the Congress by their Adjournment prevent its Return, in which Case it shall not be a Law.Every Order, Resolution, or Vote to which the Concurrence of the Senate and House of Representatives may be necessary (except on a question of Adjournment) shall be presented to the President of the United States; and before the Same shall take Effect, shall be approved by him, or being disapproved by him, shall be repassed by two thirds of the Senate and House of Representatives, according to the Rules and Limitations prescribed in the Case of a Bill.Section. 8.The Congress shall have Power To lay and collect Taxes, Duties, Imposts and Excises, to pay the Debts and provide for the common Defence and general Welfare of the United States; but all Duties, Imposts and Excises shall be uniform throughout the United States;To borrow Money on the credit of the United States;To regulate Commerce with foreign Nations, and among the several States, and with the Indian Tribes;To establish an uniform Rule of Naturalization, and uniform Laws on the subject of Bankruptcies throughout the United States;To coin Money, regulate the Value thereof, and of foreign Coin, and fix the Standard of Weights and Measures;To provide for the Punishment of counterfeiting the Securities and current Coin of the United States;To establish Post Offices and post Roads;To promote the Progress of Science and useful Arts, by securing for limited Times to Authors and Inventors the exclusive Right to their respective Writings and Discoveries;To constitute Tribunals inferior to the supreme Court;To define and punish Piracies and Felonies committed on the high Seas, and Offences against the Law of Nations;To declare War, grant Letters of Marque and Reprisal, and make Rules concerning Captures on Land and Water;To raise and support Armies, but no Appropriation of Money to that Use shall be for a longer Term than two Years;To provide and maintain a Navy;To make Rules for the Government and Regulation of the land and naval Forces;To provide for calling forth the Militia to execute the Laws of the Union, suppress Insurrections and repel Invasions;To provide for organizing, arming, and disciplining, the Militia, and for governing such Part of them as may be employed in the Service of the United States, reserving to the States respectively, the Appointment of the Officers, and the Authority of training the Militia according to the discipline prescribed by Congress;To exercise exclusive Legislation in all Cases whatsoever, over such District (not exceeding ten Miles square) as may, by Cession of particular States, and the Acceptance of Congress, become the Seat of the Government of the United States, and to exercise like Authority over all Places purchased by the Consent of the Legislature of the State in which the Same shall be, for the Erection of Forts, Magazines, Arsenals, dock-Yards, and other needful Buildings;--AndTo make all Laws which shall be necessary and proper for carrying into Execution the foregoing Powers, and all other Powers vested by this Constitution in the Government of the United States, or in any Department or Officer thereof.Section. 9.The Migration or Importation of such Persons as any of the States now existing shall think proper to admit, shall not be prohibited by the Congress prior to the Year one thousand eight hundred and eight, but a Tax or duty may be imposed on such Importation, not exceeding ten dollars for each Person.The Privilege of the Writ of Habeas Corpus shall not be suspended, unless when in Cases of Rebellion or Invasion the public Safety may require it.No Bill of Attainder or ex post facto Law shall be passed.No Capitation, or other direct, Tax shall be laid, unless in Proportion to the Census or enumeration herein before directed to be taken.No Tax or Duty shall be laid on Articles exported from any State.No Preference shall be given by any Regulation of Commerce or Revenue to the Ports of one State over those of another; nor shall Vessels bound to, or from, one State, be obliged to enter, clear, or pay Duties in another.No Money shall be drawn from the Treasury, but in Consequence of Appropriations made by Law; and a regular Statement and Account of the Receipts and Expenditures of all public Money shall be published from time to time.No Title of Nobility shall be granted by the United States: And no Person holding any Office of Profit or Trust under them, shall, without the Consent of the Congress, accept of any present, Emolument, Office, or Title, of any kind whatever, from any King, Prince, or foreign State.Section. 10.No State shall enter into any Treaty, Alliance, or Confederation; grant Letters of Marque and Reprisal; coin Money; emit Bills of Credit; make any Thing but gold and silver Coin a Tender in Payment of Debts; pass any Bill of Attainder, ex post facto Law, or Law impairing the Obligation of Contracts, or grant any Title of Nobility.No State shall, without the Consent of the Congress, lay any Imposts or Duties on Imports or Exports, except what may be absolutely necessary for executing it's inspection Laws: and the net Produce of all Duties and Imposts, laid by any State on Imports or Exports, shall be for the Use of the Treasury of the United States; and all such Laws shall be subject to the Revision and Controul of the Congress.No State shall, without the Consent of Congress, lay any Duty of Tonnage, keep Troops, or Ships of War in time of Peace, enter into any Agreement or Compact with another State, or with a foreign Power, or engage in War, unless actually invaded, or in such imminent Danger as will not admit of delay.Article. II.Section. 1.The executive Power shall be vested in a President of the United States of America. He shall hold his Office during the Term of four Years, and, together with the Vice President, chosen for the same Term, be elected, as follows:Each State shall appoint, in such Manner as the Legislature thereof may direct, a Number of Electors, equal to the whole Number of Senators and Representatives to which the State may be entitled in the Congress: but no Senator or Representative, or Person holding an Office of Trust or Profit under the United States, shall be appointed an Elector.The Electors shall meet in their respective States, and vote by Ballot for two Persons, of whom one at least shall not be an Inhabitant of the same State with themselves. And they shall make a List of all the Persons voted for, and of the Number of Votes for each; which List they shall sign and certify, and transmit sealed to the Seat of the Government of the United States, directed to the President of the Senate. The President of the Senate shall, in the Presence of the Senate and House of Representatives, open all the Certificates, and the Votes shall then be counted. The Person having the greatest Number of Votes shall be the President, if such Number be a Majority of the whole Number of Electors appointed; and if there be more than one who have such Majority, and have an equal Number of Votes, then the House of Representatives shall immediately chuse by Ballot one of them for President; and if no Person have a Majority, then from the five highest on the List the said House shall in like Manner chuse the President. But in chusing the President, the Votes shall be taken by States, the Representation from each State having one Vote; A quorum for this purpose shall consist of a Member or Members from two thirds of the States, and a Majority of all the States shall be necessary to a Choice. In every Case, after the Choice of the President, the Person having the greatest Number of Votes of the Electors shall be the Vice President. But if there should remain two or more who have equal Votes, the Senate shall chuse from them by Ballot the Vice President.The Congress may determine the Time of chusing the Electors, and the Day on which they shall give their Votes; which Day shall be the same throughout the United States.No Person except a natural born Citizen, or a Citizen of the United States, at the time of the Adoption of this Constitution, shall be eligible to the Office of President; neither shall any Person be eligible to that Office who shall not have attained to the Age of thirty five Years, and been fourteen Years a Resident within the United States.In Case of the Removal of the President from Office, or of his Death, Resignation, or Inability to discharge the Powers and Duties of the said Office, the Same shall devolve on the Vice President, and the Congress may by Law provide for the Case of Removal, Death, Resignation or Inability, both of the President and Vice President, declaring what Officer shall then act as President, and such Officer shall act accordingly, until the Disability be removed, or a President shall be elected.The President shall, at stated Times, receive for his Services, a Compensation, which shall neither be increased nor diminished during the Period for which he shall have been elected, and he shall not receive within that Period any other Emolument from the United States, or any of them.Before he enter on the Execution of his Office, he shall take the following Oath or Affirmation:--"I do solemnly swear (or affirm) that I will faithfully execute the Office of President of the United States, and will to the best of my Ability, preserve, protect and defend the Constitution of the United States."Section. 2.The President shall be Commander in Chief of the Army and Navy of the United States, and of the Militia of the several States, when called into the actual Service of the United States; he may require the Opinion, in writing, of the principal Officer in each of the executive Departments, upon any Subject relating to the Duties of their respective Offices, and he shall have Power to grant Reprieves and Pardons for Offences against the United States, except in Cases of Impeachment.He shall have Power, by and with the Advice and Consent of the Senate, to make Treaties, provided two thirds of the Senators present concur; and he shall nominate, and by and with the Advice and Consent of the Senate, shall appoint Ambassadors, other public Ministers and Consuls, Judges of the supreme Court, and all other Officers of the United States, whose Appointments are not herein otherwise provided for, and which shall be established by Law: but the Congress may by Law vest the Appointment of such inferior Officers, as they think proper, in the President alone, in the Courts of Law, or in the Heads of Departments.The President shall have Power to fill up all Vacancies that may happen during the Recess of the Senate, by granting Commissions which shall expire at the End of their next Session.Section. 3.He shall from time to time give to the Congress Information of the State of the Union, and recommend to their Consideration such Measures as he shall judge necessary and expedient; he may, on extraordinary Occasions, convene both Houses, or either of them, and in Case of Disagreement between them, with Respect to the Time of Adjournment, he may adjourn them to such Time as he shall think proper; he shall receive Ambassadors and other public Ministers; he shall take Care that the Laws be faithfully executed, and shall Commission all the Officers of the United States.Section. 4.The President, Vice President and all civil Officers of the United States, shall be removed from Office on Impeachment for, and Conviction of, Treason, Bribery, or other high Crimes and Misdemeanors.Article III.Section. 1.The judicial Power of the United States shall be vested in one supreme Court, and in such inferior Courts as the Congress may from time to time ordain and establish. The Judges, both of the supreme and inferior Courts, shall hold their Offices during good Behaviour, and shall, at stated Times, receive for their Services a Compensation, which shall not be diminished during their Continuance in Office.Section. 2.The judicial Power shall extend to all Cases, in Law and Equity, arising under this Constitution, the Laws of the United States, and Treaties made, or which shall be made, under their Authority;--to all Cases affecting Ambassadors, other public Ministers and Consuls;--to all Cases of admiralty and maritime Jurisdiction;--to Controversies to which the United States shall be a Party;--to Controversies between two or more States;-- between a State and Citizens of another State,--between Citizens of different States,--between Citizens of the same State claiming Lands under Grants of different States, and between a State, or the Citizens thereof, and foreign States, Citizens or Subjects.In all Cases affecting Ambassadors, other public Ministers and Consuls, and those in which a State shall be Party, the supreme Court shall have original Jurisdiction. In all the other Cases before mentioned, the supreme Court shall have appellate Jurisdiction, both as to Law and Fact, with such Exceptions, and under such Regulations as the Congress shall make.The Trial of all Crimes, except in Cases of Impeachment, shall be by Jury; and such Trial shall be held in the State where the said Crimes shall have been committed; but when not committed within any State, the Trial shall be at such Place or Places as the Congress may by Law have directed.Section. 3.Treason against the United States, shall consist only in levying War against them, or in adhering to their Enemies, giving them Aid and Comfort. No Person shall be convicted of Treason unless on the Testimony of two Witnesses to the same overt Act, or on Confession in open Court.The Congress shall have Power to declare the Punishment of Treason, but no Attainder of Treason shall work Corruption of Blood, or Forfeiture except during the Life of the Person attainted.Article. IV.Section. 1.Full Faith and Credit shall be given in each State to the public Acts, Records, and judicial Proceedings of every other State. And the Congress may by general Laws prescribe the Manner in which such Acts, Records and Proceedings shall be proved, and the Effect thereof.Section. 2.The Citizens of each State shall be entitled to all Privileges and Immunities of Citizens in the several States.A Person charged in any State with Treason, Felony, or other Crime, who shall flee from Justice, and be found in another State, shall on Demand of the executive Authority of the State from which he fled, be delivered up, to be removed to the State having Jurisdiction of the Crime.No Person held to Service or Labour in one State, under the Laws thereof, escaping into another, shall, in Consequence of any Law or Regulation therein, be discharged from such Service or Labour, but shall be delivered up on Claim of the Party to whom such Service or Labour may be due.Section. 3.New States may be admitted by the Congress into this Union; but no new State shall be formed or erected within the Jurisdiction of any other State; nor any State be formed by the Junction of two or more States, or Parts of States, without the Consent of the Legislatures of the States concerned as well as of the Congress.The Congress shall have Power to dispose of and make all needful Rules and Regulations respecting the Territory or other Property belonging to the United States; and nothing in this Constitution shall be so construed as to Prejudice any Claims of the United States, or of any particular State.Section. 4.The United States shall guarantee to every State in this Union a Republican Form of Government, and shall protect each of them against Invasion; and on Application of the Legislature, or of the Executive (when the Legislature cannot be convened), against domestic Violence.Article. V.The Congress, whenever two thirds of both Houses shall deem it necessary, shall propose Amendments to this Constitution, or, on the Application of the Legislatures of two thirds of the several States, shall call a Convention for proposing Amendments, which, in either Case, shall be valid to all Intents and Purposes, as Part of this Constitution, when ratified by the Legislatures of three fourths of the several States, or by Conventions in three fourths thereof, as the one or the other Mode of Ratification may be proposed by the Congress; Provided that no Amendment which may be made prior to the Year One thousand eight hundred and eight shall in any Manner affect the first and fourth Clauses in the Ninth Section of the first Article; and that no State, without its Consent, shall be deprived of its equal Suffrage in the Senate.Article. VI.All Debts contracted and Engagements entered into, before the Adoption of this Constitution, shall be as valid against the United States under this Constitution, as under the Confederation.This Constitution, and the Laws of the United States which shall be made in Pursuance thereof; and all Treaties made, or which shall be made, under the Authority of the United States, shall be the supreme Law of the Land; and the Judges in every State shall be bound thereby, any Thing in the Constitution or Laws of any State to the Contrary notwithstanding.The Senators and Representatives before mentioned, and the Members of the several State Legislatures, and all executive and judicial Officers, both of the United States and of the several States, shall be bound by Oath or Affirmation, to support this Constitution; but no religious Test shall ever be required as a Qualification to any Office or public Trust under the United States.Article. VII.The Ratification of the Conventions of nine States, shall be sufficient for the Establishment of this Constitution between the States so ratifying the Same.The Word, "the," being interlined between the seventh and eighth Lines of the first Page, the Word "Thirty" being partly written on an Erazure in the fifteenth Line of the first Page, The Words "is tried" being interlined between the thirty second and thirty third Lines of the first Page and the Word "the" being interlined between the forty third and forty fourth Lines of the second Page.Attest William Jackson Secretarydone in Convention by the Unanimous Consent of the States present the Seventeenth Day of September in the Year of our Lord one thousand seven hundred and Eighty seven and of the Independance of the United States of America the Twelfth In witness whereof We have hereunto subscribed our Names,

为了方便,我直接将constitution.txt文件粘贴进来了,可以直接复制即可使用,避免下载问题麻烦首先看实例:

stylecloud.gen_stylecloud(file_path="constitution.txt",icon_name="fab fa-twitter",palette="cartocolors.diverging.TealRose_7",background_color="black",output_name="pic/fab-fa-twitter-black.jpg",
)stylecloud.gen_stylecloud(file_path="constitution.txt",icon_name="fab fa-twitter",palette="cartocolors.diverging.TealRose_7",background_color="white",output_name="pic/fab-fa-twitter-white.jpg",
)stylecloud.gen_stylecloud(file_path="constitution.txt",icon_name="fab fa-linkedin-in",background_color="orange",output_name="pic/fab-fa-linkedin-in-orange.jpg",
)
stylecloud.gen_stylecloud(file_path="constitution.txt",icon_name="fab fa-linkedin-in",background_color="black",output_name="pic/fab-fa-linkedin-in-black.jpg",
)

结果如下:

所有的参数都是可以自己自有地调节使用的,这里可以组合出来很多有趣有意思的词云图,我就不再一一粘贴代码了简单看下效果吧:

感兴趣的话就动手试试吧!

酷炫多彩的个性化词云可视化相关推荐

  1. Rstudio 实现 爬虫 文本分词 个性化词云设计--我爱中国我爱党

    Rstudio 爬虫 文本分词个性化词云设计 目录 1.环境准备,加载依赖 2.rvest 爬虫,数据爬取 3.jiebaR用于分词,词频统计 4.wordcloud2 结果可视化 ========= ...

  2. 手把手:R语言文本挖掘和词云可视化实践

    互联网时代,大量的新闻信息.网络交互.舆情信息以文本形式存储在数据库中,如何利用数据分析和文本挖掘的算法,将海量文本的价值挖掘出来,成为我们团队近期的一个研究方向,本案例就是我们的一个初步尝试.飞信群 ...

  3. python英文词云代码_使用python实现个性化词云的方法

    先上图片 词云图 需要模板 pip install jieba pip install wordcloud 还需要安装另外两个东西这两个我也不太懂借鉴百度写上去的 pip install scipy ...

  4. 下c语言实现wc_用 Python 实现词云可视化

    词云是一种非常漂亮的可视化展示方式,正所谓一图胜过千言万语,词云在之前的项目中我也有过很多的使用,可能对于我来说,一种很好的自我介绍方式就是词云吧,就像下面这样的: 个人觉还是会比枯燥的文字语言描述性 ...

  5. D3临摹作业_分词与词云可视化(西安交大国家艺术基金数据可视化培训第28天)

    第十二章  分词与词云可视化 第一节 词云图 概念:一种富文本信息可视化技术,通过布局算法用文字大小表示词频,辅以多种颜色,直观的反映词组重要性差异,展示文本关键摘要信息.完整的词云分析包括:分词.词 ...

  6. wordcloud词云可视化

    安装: pip install wordcloud(有时会有VC++ 14缺失的问题) 解决方案: 在github下载wordcloud的包(https://github.com/amueller/w ...

  7. 文本数据的词云可视化

    1.使用python实现文本数据的词云可视化,阐述词云原理,数据源可以自行选定: 2.实现文本数据的one-hot编码.Bag-of-word模型,将过程阐述清楚,数据源可以自行选定: 词云可视化 随 ...

  8. 用Python做词云可视化带你分析海贼王、火影和死神三大经典动漫

    对于动漫爱好者来说,海贼王.火影.死神三大动漫神作你肯定肯定不陌生了.小编身边很多的同事仍然深爱着这些经典神作,可见"中毒"至深.今天小编利用Python大法带大家分析一下这些神作 ...

  9. Python大佬用词云可视化带你分析海贼王、火影和死神三大经典动漫

    对于动漫爱好者来说,海贼王.火影.死神三大动漫神作你肯定肯定不陌生了.小编身边很多的同事仍然深爱着这些经典神作,可见"中毒"至深.利用Python大法带大家分析一下这些神作,看看这 ...

最新文章

  1. TextView 的ScrollView滚动效果
  2. JAVA程序设计心得001
  3. composer切换源_Composer具体安装方法
  4. 如何查看mysql8.0的默认密码_MySQL8.0安装之后查找默认密码
  5. Spring AOP知识详解
  6. Spark之SparkSQL数据源
  7. bash 将二进制转换为十进制_用‘栈的思想编写一个十进制转换二进制、八进制或十六进制的程序...
  8. GitHub 遭黑客攻击勒索;苹果夸大 iPhone 电池续航时间;全球第二大暗网被摧毁 | 极客头条...
  9. Autotools发展史
  10. 计算机组成原理袁春风知识点,计算机组成原理袁春风chap.pdf
  11. 约瑟夫问题的数学解法
  12. PIN码-使用与解决办法
  13. 程序员 写作_如何经常写作可以使您成为更好的程序员
  14. NOIP模拟题17.9.26
  15. ToDoList中文版(任务管理软件)v7.1.5.0
  16. QT环境搭建及常见错误
  17. MFC的导航窗格浮窗设计
  18. spring的两大核心
  19. 在pe下怎样重装服务器系统,PE怎么重装系统|PE系统重装图文教程
  20. 十位世界级顶尖投资大师的投资哲学:忍耐、聚焦、坚定

热门文章

  1. 注册表残留内容的删除
  2. <计算机视觉 六> 深度学习目标检测模型的评估标准
  3. 震惊!为了家人请不要这样对待自己的身体!
  4. Word论文写作公式居中、编号右对齐
  5. USB无法debug调试:because an app is obscuring a permission request settings cab't verify your resonse
  6. windows上mosquitto安装及简单使用
  7. Assignment | 05-week3 -Part_2-Trigger Word Detection
  8. Linux远程控制音乐播放,总结一下linux远程控制方法
  9. 520被女朋友三番两次拉黑后,我用 Python 写了个“舔狗”必备神器
  10. 修改机顶盒设置移动焦点颜色