人工智能與Python教程_第1頁(yè)
人工智能與Python教程_第2頁(yè)
人工智能與Python教程_第3頁(yè)
人工智能與Python教程_第4頁(yè)
人工智能與Python教程_第5頁(yè)
已閱讀5頁(yè),還剩159頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

toria1s in

s 尸LY EASY G

www.

tutoriaIs

https://

/tutorialspointindlia

/tutorialspoi,nt

AIwithPython

PAGE\*roman

iii

AbouttheTutorial

Artificialintelligenceistheintelligencedemonstratedbymachines,incontrasttotheintelligencedisplayedbyhumans.

ThistutorialcoversthebasicconceptsofvariousfieldsofartificialintelligencelikeArtificialNeuralNetworks,NaturalLanguageProcessing,MachineLearning,DeepLearning,Geneticalgorithmsetc.,anditsimplementationinPython.

Audience

Thistutorialwillbeusefulforgraduates,postgraduates,andresearchstudentswhoeitherhaveaninterestinthissubjectorhavethissubjectasapartoftheircurriculum.Thereadercanbeabeginneroranadvancedlearner.

Prerequisites

WeassumethatthereaderhasbasicknowledgeaboutArtificialIntelligenceandPythonprogramming.He/sheshouldbeawareaboutbasicterminologiesusedinAIalongwithsomeusefulpythonpackageslikenltk,OpenCV,pandas,OpenAIGym,etc.

Copyright&Disclaimer

?Copyright2016byTutorialsPoint(I)Pvt.Ltd.

Allthecontentandgraphicspublishedinthise-bookarethepropertyofTutorialsPoint(I)Pvt.Ltd.Theuserofthise-bookisprohibitedtoreuse,retain,copy,distributeorrepublishanycontentsorapartofcontentsofthise-bookinanymannerwithoutwrittenconsentofthepublisher.

Westrivetoupdatethecontentsofourwebsiteandtutorialsastimelyandaspreciselyaspossible,however,thecontentsmaycontaininaccuraciesorerrors.TutorialsPoint(I)Pvt.Ltd.providesnoguaranteeregardingtheaccuracy,timelinessorcompletenessofourwebsiteoritscontentsincludingthistutorial.Ifyoudiscoveranyerrorsonourwebsiteorinthistutorial,pleasenotifyusat

contact@

TableofContents

TOC\o"1-2"\h\z\u

AbouttheTutorial i

Audience i

Prerequisites i

Copyright&Disclaimer i

TableofContents ii

AIwithPython–PrimerConcepts 1

BasicConceptofArtificialIntelligence(AI) 1

TheNecessityofLearningAI 1

WhatisIntelligence? 2

WhatisIntelligenceComposedOf? 3

Learning?l 4

What’sInvolvedinAI 6

ApplicationofAI 6

CognitiveModeling:SimulatingHumanThinkingProcedure 7

Agent&Environment 8

AIwithPython–GettingStarted 9

WhyPythonforAI 9

FeaturesofPython 9

InstallingPython 10

SettingupPATH 11

RunningPython 12

ScriptfromtheCommand-line 13

IntegratedDevelopmentEnvironment 13

AIwithPython–MachineLearning 15

TypesofMachineLearning(ML) 15

MostCommonMachineLearningAlgorithms 16

AIwithPython–DataPreparation 20

PreprocessingtheData 20

TechniquesforDataPreprocessing 21

LabelingtheData 23

AIwithPython–SupervisedLearning:Classification 26

StepsforBuildingaClassifierinPython 26

BuildingClassifierinPython 29

LogisticRegression 34

DecisionTreeClassifier 37

RandomForestClassifier 39

Performanceofaclassifier 40

ClassImbalanceProblem 42

EnsembleTechniques 43

AIwithPython–SupervisedLearning:Regression 44

BuildingRegressorsinPython 44

AIwithPython–LogicProgramming 49

HowtoSolveProblemswithLogicProgramming 49

InstallingUsefulPackages 50

ExamplesofLogicProgramming 50

CheckingforPrimeNumbers 51

SolvingPuzzles 52

AIwithPython–UnsupervisedLearning:Clustering 55

WhatisClustering? 55

AlgorithmsforClusteringtheData 55

MeasuringtheClusteringPerformance 61

CalculatingSilhouetteScore 61

FindingNearestNeighbors 63

K-NearestNeighborsClassifier 65

AIwithPython–NaturalLanguageProcessing 69

ComponentsofNLP 69

DifficultiesinNLU 69

NLPTerminology 70

StepsinNLP 70

AIwithPython–NLTKpackage 72

ImportingNLTK 72

DownloadingNLTK’sData 72

InstallingOtherNecessaryPackages 73

ConceptofTokenization,Stemming,andLemmatization 73

Chunking:DividingDataintoChunks 75

Typesofchunking 76

BagofWord(BoW)Model 77

ConceptoftheStatistics 78

BuildingaBagofWordsModelinNLTK 79

SolvingProblems 79

TopicModeling:IdentifyingPatternsinTextData 84

AlgorithmsforTopicModeling 84

AIwithPython–AnalyzingTimeSeriesData 86

Introduction 86

InstallingUsefulPackages 86

Pandas:Handling,SlicingandExtractingStatisticfromTimeSeriesData 87

ExtractingStatisticfromTimeSeriesData 91

AnalyzingSequentialDatabyHiddenMarkovModel(HMM) 95

Example:AnalysisofStockMarketdata 96

AIwithPython–SpeechRecognition 99

BuildingaSpeechRecognizer 99

VisualizingAudioSignals-ReadingfromaFileandWorkingonit 100

CharacterizingtheAudioSignal:TransformingtoFrequencyDomain 102

GeneratingMonotoneAudioSignal 104

FeatureExtractionfromSpeech 106

RecognitionofSpokenWords 108

AIwithPython–HeuristicSearch 111

ConceptofHeuristicSearchinAI 111

DifferencebetweenUninformedandInformedSearch 111

RealWorldProblemSolvedbyConstraintSatisfaction 112

AIwithPython–Gaming 115

SearchAlgorithms 115

CombinationalSearch 115

MinimaxAlgorithm 115

Alpha-BetaPruning 116

NegamaxAlgorithm 116

BuildingBotstoPlayGames 116

ABottoPlayLastCoinStanding 116

ABottoPlayTicTacToe 119

AIwithPython–NeuralNetworks 122

WhatisArtificialNeuralNetworks(ANN) 122

InstallingUsefulPackages 122

BuildingNeuralNetworks 122

PerceptronbasedClassifier 123

Single-LayerNeuralNetworks 124

Multi-LayerNeuralNetworks 127

AIwithPython–ReinforcementLearning 131

BasicsofReinforcementLearning 131

BuildingBlocks:EnvironmentandAgent 131

ConstructinganEnvironmentwithPython 133

ConstructingalearningagentwithPython 134

AIwithPython–GeneticAlgorithms 135

WhatareGeneticAlgorithms? 135

HowtoUseGAforOptimizationProblems? 135

InstallingNecessaryPackages 136

ImplementingSolutionsusingGeneticAlgorithms 136

AIwithPython–ComputerVision 142

ComputerVision 142

ComputerVisionVsImageProcessing 142

InstallingUsefulPackages 143

Reading,WritingandDisplayinganImage 144

ColorSpaceConversion 145

EdgeDetection 147

FaceDetection 148

EyeDetection 149

AIwithPython–DeepLearning 151

MachineLearningv/sDeepLearning 151

ConvolutionalNeuralNetwork(CNN) 151

InstallingUsefulPythonPackages 152

BuildingLinearRegressorusingANN 153

ImageClassifier:AnApplicationofDeepLearning 154

PAGE

1

AIwithPython

AIwithPython–PrimerConcepts

Sincetheinventionofcomputersormachines,theircapabilitytoperformvarioustaskshasexperiencedanexponentialgrowth.Humanshavedevelopedthepowerofcomputersystemsintermsoftheirdiverseworkingdomains,theirincreasingspeed,andreducingsizewithrespecttotime.

AbranchofComputerSciencenamedArtificialIntelligencepursuescreatingthecomputersormachinesasintelligentashumanbeings.

BasicConceptofArtificialIntelligence(AI)

AccordingtothefatherofArtificialIntelligence,JohnMcCarthy,itis“Thescienceandengineeringofmakingintelligentmachines,especiallyintelligentcomputerprograms”.

ArtificialIntelligenceisawayofmakingacomputer,acomputer-controlledrobot,orasoftwarethinkintelligently,inthesimilarmannertheintelligenthumansthink.AIisaccomplishedbystudyinghowhumanbrainthinksandhowhumanslearn,decide,andworkwhiletryingtosolveaproblem,andthenusingtheoutcomesofthisstudyasabasisofdevelopingintelligentsoftwareandsystems.

Whileexploitingthepowerofthecomputersystems,thecuriosityofhuman,leadhimtowonder,“Canamachinethinkandbehavelikehumansdo?”

Thus,thedevelopmentofAIstartedwiththeintentionofcreatingsimilarintelligenceinmachinesthatwefindandregardhighinhumans.

TheNecessityofLearningAI

AsweknowthatAIpursuescreatingthemachinesasintelligentashumanbeings.TherearenumerousreasonsforustostudyAI.Thereasonsareasfollows:

AIcanlearnthroughdata

Inourdailylife,wedealwithhugeamountofdataandhumanbraincannotkeeptrackofsomuchdata.Thatiswhyweneedtoautomatethethings.Fordoingautomation,weneedtostudyAIbecauseitcanlearnfromdataandcandotherepetitivetaskswithaccuracyandwithouttiredness.

AIcanteachitself

Itisverynecessarythatasystemshouldteachitselfbecausethedataitselfkeepschangingandtheknowledgewhichisderivedfromsuchdatamustbeupdatedconstantly.WecanuseAItofulfillthispurposebecauseanAIenabledsystemcanteachitself.

AIcanrespondinrealtime

Artificialintelligencewiththehelpofneuralnetworkscananalyzethedatamoredeeply.Duetothiscapability,AIcanthinkandrespondtothesituationswhicharebasedontheconditionsinrealtime.

AIwithPython

PAGE

2

AIachievesaccuracy

Withthehelpofdeepneuralnetworks,AIcanachievetremendousaccuracy.AIhelpsinthefieldofmedicinetodiagnosediseasessuchascancerfromtheMRIsofpatients.

AIcanorganizedatatogetmostoutofit

Thedataisanintellectualpropertyforthesystemswhichareusingself-learningalgorithms.WeneedAItoindexandorganizethedatainawaythatitalwaysgivesthebestresults.

UnderstandingIntelligence

WithAI,smartsystemscanbebuilt.Weneedtounderstandtheconceptofintelligencesothatourbraincanconstructanotherintelligencesystemlikeitself.

WhatisIntelligence?

Theabilityofasystemtocalculate,reason,perceiverelationshipsandanalogies,learnfromexperience,storeandretrieveinformationfrommemory,solveproblems,comprehendcomplexideas,usenaturallanguagefluently,classify,generalize,andadaptnewsituations.

TypesofIntelligence

AsdescribedbyHowardGardner,anAmericandevelopmentalpsychologist,Intelligencecomesinmultifold:

Intelligence

Description

Example

Linguisticintelligence

Theabilitytospeak,recognize,andusemechanismsofphonology(speechsounds),syntax(grammar),andsemantics(meaning).

Narrators,Orators

Musicalintelligence

Theabilitytocreate,communicatewith,andunderstandmeaningsmadeofsound,understandingofpitch,rhythm.

Musicians,Singers,Composers

Logical-mathematicalintelligence

Theabilitytouseandunderstandrelationshipsintheabsenceofactionorobjects.Itisalsotheabilitytounderstandcomplexandabstractideas.

Mathematicians,Scientists

Spatialintelligence

Theabilitytoperceivevisualorspatialinformation,changeit,andre-createvisualimageswithoutreferencetotheobjects,construct3D

Map readers,Astronauts,Physicists

images,andtomoveandrotatethem.

Bodily-Kinestheticintelligence

Theabilitytousecompleteorpartofthebodytosolveproblemsorfashionproducts,controloverfineandcoarsemotorskills,andmanipulatetheobjects.

Players,Dancers

Intra-personalintelligence

Theabilitytodistinguishamongone’sownfeelings,intentions,andmotivations.

GautamBuddhha

Interpersonalintelligence

Theabilitytorecognizeandmakedistinctionsamongotherpeople’sfeelings,beliefs,andintentions.

MassCommunicators,Interviewers

Youcansayamachineorasystemisartificiallyintelligentwhenitisequippedwithatleastoneorallintelligencesinit.

WhatisIntelligenceComposedOf?

Theintelligenceisintangible.Itiscomposedof?

Reasoning

Learning

ProblemSolving

Perception

LinguisticIntelligence

Letusgothroughallthecomponentsbriefly?

Reasoning

Itisthesetofprocessesthatenableustoprovidebasisforjudgement,makingdecisions,andprediction.Therearebroadlytwotypes?

InductiveReasoning

DeductiveReasoning

Itconductsspecificobservationstomakesbroadgeneralstatements.

Itstartswithageneralstatement and

examines thepossibilitiestoreachaspecific, logicalconclusion.

Evenifallofthepremisesaretrueinastatement,inductivereasoningallowsfortheconclusiontobefalse.

Ifsomethingistrueofaclassofthingsingeneral,itisalsotrueforallmembersofthatclass.

Example?"Nitaisateacher.Nitaisstudious.Therefore,Allteachersarestudious."

Example?"Allwomenofageabove60yearsaregrandmothers.Shaliniis65years.Therefore,Shaliniisagrandmother."

Learning?l

Theabilityoflearningispossessedbyhumans,particularspeciesofanimals,andAI-enabledsystems.Learningiscategorizedasfollows?

AuditoryLearning

Itislearningbylisteningandhearing.Forexample,studentslisteningtorecordedaudiolectures.

EpisodicLearning

Tolearnbyrememberingsequencesofeventsthatonehaswitnessedorexperienced.Thisislinearandorderly.

MotorLearning

Itislearningbyprecisemovementofmuscles.Forexample,pickingobjects,writing,etc.

ObservationalLearning

Tolearnbywatchingandimitatingothers.Forexample,childtriestolearnbymimickingherparent.

PerceptualLearning

Itislearningtorecognizestimulithatonehasseenbefore.Forexample,identifyingandclassifyingobjectsandsituations.

RelationalLearning

Itinvolveslearningtodifferentiateamongvariousstimulionthebasisofrelationalproperties,ratherthanabsoluteproperties.ForExample,Adding‘littleless’saltatthetimeofcookingpotatoesthatcameupsaltylasttime,whencookedwithaddingsayatablespoonofsalt.

SpatialLearning?Itislearningthroughvisualstimulisuchasimages,colors,maps,etc.Forexample,Apersoncancreateroadmapinmindbeforeactuallyfollowingtheroad.

Stimulus-ResponseLearning?Itislearningtoperformaparticularbehaviorwhenacertainstimulusispresent.Forexample,adograisesitsearonhearingdoorbell.

ProblemSolving

Itistheprocessinwhichoneperceivesandtriestoarriveatadesiredsolutionfromapresentsituationbytakingsomepath,whichisblockedbyknownorunknownhurdles.

Problemsolvingalsoincludesdecisionmaking,whichistheprocessofselectingthebestsuitablealternativeoutofmultiplealternativestoreachthedesiredgoal.

Perception

Itistheprocessofacquiring,interpreting,selecting,andorganizingsensoryinformation.

Perceptionpresumessensing.Inhumans,perceptionisaidedbysensoryorgans.InthedomainofAI,perceptionmechanismputsthedataacquiredbythesensorstogetherinameaningfulmanner.

LinguisticIntelligence

Itisone’sabilitytouse,comprehend,speak,andwritetheverbalandwrittenlanguage.Itisimportantininterpersonalcommunication.

What’sInvolvedinAI

Artificialintelligenceisavastareaofstudy.Thisfieldofstudyhelpsinfindingsolutionstorealworldproblems.

LetusnowseethedifferentfieldsofstudywithinAI:

MachineLearning

ItisoneofthemostpopularfieldsofAI.Thebasicconceptofthisfiledistomakethemachinelearningfromdataasthehumanbeingscanlearnfromhis/herexperience.Itcontainslearningmodelsonthebasisofwhichthepredictionscanbemadeonunknowndata.

Logic

Itisanotherimportantfieldofstudyinwhichmathematicallogicisusedtoexecutethecomputerprograms.Itcontainsrulesandfactstoperformpatternmatching,semanticanalysis,etc.

Searching

Thisfieldofstudyisbasicallyusedingameslikechess,tic-tac-toe.Searchalgorithmsgivetheoptimalsolutionaftersearchingthewholesearchspace.

Artificialneuralnetworks

Thisisanetworkofefficientcomputingsystemsthecentralthemeofwhichisborrowedfromtheanalogyofbiologicalneuralnetworks.ANNcanbeusedinrobotics,speechrecognition,speechprocessing,etc.

GeneticAlgorithm

Geneticalgorithmshelpinsolvingproblemswiththeassistanceofmorethanoneprogram.Theresultwouldbebasedonselectingthefittest.

KnowledgeRepresentation

Itisthefieldofstudywiththehelpofwhichwecanrepresentthefactsinawaythemachinethatisunderstandabletothemachine.Themoreefficientlyknowledgeisrepresented;themoresystemwouldbeintelligent.

ApplicationofAI

Inthissection,wewillseethedifferentfieldssupportedbyAI:

Gaming

AIplayscrucialroleinstrategicgamessuchaschess,poker,tic-tac-toe,etc.,wheremachinecanthinkoflargenumberofpossiblepositionsbasedonheuristicknowledge.

NaturalLanguageProcessing

Itispossibletointeractwiththecomputerthatunderstandsnaturallanguagespokenbyhumans.

ExpertSystems

Therearesomeapplicationswhichintegratemachine,software,andspecialinformationtoimpartreasoningandadvising.Theyprovideexplanationandadvicetotheusers.

VisionSystems

Thesesystemsunderstand,interpret,andcomprehendvisualinputonthecomputer.Forexample,

Aspyingaeroplanetakesphotographs,whichareusedtofigureoutspatialinformationormapoftheareas.

Doctorsuseclinicalexpertsystemtodiagnosethepatient.

Policeusecomputersoftwarethatcanrecognizethefaceofcriminalwiththestoredportraitmadebyforensicartist.

SpeechRecognition

Someintelligentsystemsarecapableofhearingandcomprehendingthelanguageintermsofsentencesandtheirmeaningswhileahumantalkstoit.Itcanhandledifferentaccents,slangwords,noiseinthebackground,changeinhuman’snoiseduetocold,etc.

HandwritingRecognition

Thehandwritingrecognitionsoftwarereadsthetextwrittenonpaperbyapenoronscreenbyastylus.Itcanrecognizetheshapesofthelettersandconvertitintoeditabletext.

IntelligentRobots

Robotsareabletoperformthetasksgivenbyahuman.Theyhavesensorstodetectphysicaldatafromtherealworldsuchaslight,heat,temperature,movement,sound,bump,andpressure.Theyhaveefficientprocessors,multiplesensorsandhugememory,toexhibitintelligence.Inaddition,theyarecapableoflearningfromtheirmistakesandtheycanadapttothenewenvironment.

CognitiveModeling:SimulatingHumanThinkingProcedure

Cognitivemodelingisbasicallythefieldofstudywithincomputersciencethatdealswiththestudyandsimulatingthethinkingprocessofhumanbeings.ThemaintaskofAIistomakemachinethinklikehuman.Themostimportantfeatureofhumanthinkingprocessisproblemsolving.Thatiswhymoreorlesscognitivemodelingtriestounderstandhowhumanscansolvetheproblems.AfterthatthismodelcanbeusedforvariousAIapplicationssuchasmachinelearning,robotics,naturallanguageprocessing,etc.Followingisthediagramofdifferentthinkinglevelsofhumanbrain:

Cognitive

Behaviora

Physical

Kinematic

Geometri

Agent&Environment

Inthissection,wewillfocusontheagentandenvironmentandhowthesehelpinArtificialIntelligence.

Agent

Anagentisanythingthatcanperceiveitsenvironmentthroughsensorsandactsuponthatenvironmentthrougheffectors.

Ahumanagenthassensoryorganssuchaseyes,ears,nose,tongueandskinparalleltothesensors,andotherorganssuchashands,legs,mouth,foreffectors.

Aroboticagentreplacescamerasandinfraredrangefindersforthesensors,andvariousmotorsandactuatorsforeffectors.

Asoftwareagenthasencodedbitstringsasitsprogramsandactions.

Environment

Someprogramsoperateinanentirelyartificialenvironmentconfinedtokeyboardinput,database,computerfilesystemsandcharacteroutputonascreen.

Incontrast,somesoftwareagents(softwarerobotsorsoftbots)existinrich,unlimitedsoftbotsdomains.Thesimulatorhasaverydetailed,complexenvironment.Thesoftwareagentneedstochoosefromalongarrayofactionsinrealtime.Asoftbotisdesignedtoscantheonlinepreferencesofthecustomerandshowsinterestingitemstothecustomerworksintherealaswellasanartificialenvironment.

PAGE

9

AIwithPython

AIwithPython–GettingStarted

Inthischapter,wewilllearnhowtogetstartedwithPython.WewillalsounderstandhowPythonhelpsforArtificialIntelligence.

WhyPythonforAI

Artificialintelligenceisconsideredtobethetrendingtechnologyofthefuture.Alreadythereareanumberofapplicationsmadeonit.Duetothis,manycompaniesandresearchersaretakinginterestinit.ButthemainquestionthatariseshereisthatinwhichprogramminglanguagecantheseAIapplicationsbedeveloped?TherearevariousprogramminglanguageslikeLisp,Prolog,C++,JavaandPython,whichcanbeusedfordevelopingapplicationsofAI.Amongthem,Pythonprogramminglanguagegainsahugepopularityandthereasonsareasfollows:

Simplesyntax&lesscoding

PythoninvolvesverylesscodingandsimplesyntaxamongotherprogramminglanguageswhichcanbeusedfordevelopingAIapplications.Duetothisfeature,thetestingcanbeeasierandwecanfocusmoreonprogramming.

InbuiltlibrariesforAIprojects

AmajoradvantageforusingPythonforAIisthatitcomeswithinbuiltlibraries.PythonhaslibrariesforalmostallkindsofAIprojects.Forexample,NumPy,SciPy,matplotlib,nltk,SimpleAIaresometheimportantinbuiltlibrariesofPython.

Opensource:Pythonisanopensourceprogramminglanguage.Thismakesitwidelypopularinthecommunity.

Canbeusedforbroadrangeofprogramming:Pythoncanbeusedforabroadrangeofprogrammingtaskslikesmallshellscripttoenterprisewebapplications.ThisisanotherreasonPythonissuitableforAIprojects.

FeaturesofPython

Pythonisahigh-level,interpreted,interactiveandobject-orientedscriptinglanguage.Pythonisdesignedtobehighlyreadable.ItusesEnglishkeywordsfrequentlywhereasotherlanguagesusepunctuation,andithasfewersyntacticalconstructionsthanotherlanguages.Python'sfeaturesincludethefollowing?

Easy-to-learn?Pythonhasfewkeywords,simplestructure,andaclearlydefinedsyntax.Thisallowsthestudenttopickupthelanguagequickly.

Easy-to-read?Pythoncodeismoreclearlydefinedandvisibletotheeyes.

Easy-to-maintain?Python'ssourcecodeisfairlyeasy-to-maintain.

Abroadstandardlibrary?Python'sbulkofthelibraryisveryportableandcross-platformcompatibleonUNIX,Windows,andMacintosh.

AIwithPython

PAGE

10

InteractiveMode?Pythonhassupportforaninteractivemodewhichallowsinteractivetestinganddebuggingofsnippetsofcode.

Portable?Pythoncanrunonawidevarietyofhardwareplatformsandhasthesameinterfaceonallplatforms.

Extendable?Wecanaddlow-levelmodulestothePythoninterpreter.Thesemodulesenableprogrammerstoaddtoorcustomizetheirtoolstobemoreefficient.

Databases?Pythonprovidesinterfacestoallmajorcommercialdatabases.

GUIProgramming?PythonsupportsGUIapplicationsthatcanbecreatedandportedtomanysystemcalls,librariesandwindowssystems,suchasWindowsMFC,Macintosh,andtheXWindowsystemofUnix.

Scalable?Pythonprovidesabetterstructureandsupportforlargeprogramsthanshellscripting.

ImportantfeaturesofPython

LetusnowconsiderthefollowingimportantfeaturesofPython:

ItsupportsfunctionalandstructuredprogrammingmethodsaswellasOOP.

Itcanbeusedasascriptinglanguageorcanbecompiledtobyte-codeforbuildinglargeapplications.

Itprovidesveryhigh-leveldynamicdatatypesandsupportsdynamictypechecking.

Itsupportsautomaticgarbagecollection.

ItcanbeeasilyintegratedwithC,C++,COM,ActiveX,CORBA,andJava.

InstallingPython

Pythondistributionisavailableforalargenumberofplatforms.YouneedtodownloadonlythebinarycodeapplicableforyourplatformandinstallPython.

Ifthebinarycodeforyourplatformisnotavailable,youneedaCcompilertocompilethesourcecodemanually.Compilingthesourcecodeoffersmoreflexibilityintermsofchoiceoffeaturesthatyourequireinyourinstallation.

HereisaquickoverviewofinstallingPythononvariousplatforms?

UnixandLinuxInstallation

FollowthesestepstoinstallPythononUnix/Linuxmachine.

OpenaWebbrowserandgoto

/downloads/

.

FollowthelinktodownloadzippedsourcecodeavailableforUnix/Linux.

Downloadandextractfiles.

EditingtheModules/Setupfileifyouwanttocustomizesomeoptions.

run./configurescript

make

makeinstall

ThisinstallsPythonatthestandardlocation/usr/local/binanditslibrariesat/usr/local/lib/pythonXXwhereXXistheversionofPython.

WindowsInstallation

FollowthesestepstoinstallPythononWindowsmachine.

OpenaWebbrowserandgoto

/downloads/

.

FollowthelinkfortheWindowsinstallerpython-XYZ.msifilewhereXYZistheversionyouneedtoinstall.

Tousethisinstallerpython-XYZ.msi,theWindowssystemmustsupportMicrosoftInstaller2.0.SavetheinstallerfiletoyourlocalmachineandthenrunittofindoutifyourmachinesupportsMSI.

Runthedownloadedfile.ThisbringsupthePythoninstallwizard,whichisreallyeasytouse.Justacceptthedefaultsettingsandwaituntiltheinstallisfinished.

MacintoshInstallation

IfyouareonMacOSX,itisrecommendedthatyouuseHomebrewtoinstallPython3.ItisagreatpackageinstallerforMacOSXanditisreallyeasytouse.Ifyoudon'thaveHomebrew,youcaninstallitusingthefollowingcommand:

$ruby-e"$(curl-fsSL/Homebrew/install/master/install)"

Wecanupdatethepackagemanagerwiththecommandbelow:

$brewupdate

NowrunthefollowingcommandtoinstallPython3onyoursystem:

$brewinstallpython3

SettingupPATH

Programsandotherexecutablefilescanbeinmanydirectories,sooperatingsystemsprovideasearchpaththatliststhedirectoriesthattheOSsearchesforexecutables.

Thepathisstoredinanenvironmentvariable,whichisanamedstringmaintainedbytheoperatingsystem.Thisvariablecontainsinformationavailabletothecommandshellandotherprograms.

ThepathvariableisnamedasPATHinUnixorPathinWindows(Unixiscase-sensitive;Windowsisnot).

InMacOS,theinstallerhandlesthepathdetails.ToinvokethePythoninterpreterfromanyparticulardirectory,youmustaddthePythondirectorytoyourpath.

SettingPathatUnix/Linux

ToaddthePythondirectorytothepathforaparticularsessioninUnix?

Inthecshshell?typesetenvPATH"$PATH:/usr/local/bin/python"andpressEnter.

In the bash shell (Linux)? type exportATH="$PATH:/usr/local/bin/python"andpressEnter.

Intheshor

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論