Sunday, 26 November 2017

Compute glidande medelvärde python


Scikits. timeseries-modulen genomgår inte längre aktiv utveckling. Det finns en enastående lista över fel som sannolikt inte kommer att lösas. Planen är att kärnfunktionen i denna modul ska implementeras i pandor. Om du vill se den här modulen leva på oberoende av pandor, var god att gaffla koden och ta den över. Scikits. timeseries-modulen ger klasser och funktioner för att manipulera, rapportera och plotta tidsserier av olika frekvenser. Fokus ligger på bekväm dataåtkomst och manipulation samtidigt som man utnyttjar den befintliga matematiska funktionaliteten i numpy och scipy. Om följande scenarier låter bekanta för dig så kommer du troligen att hitta modulen scikits. timeseries. Jämför många tidsserier med olika dataområden (t. ex. aktiekurser) Skapa tidsserieplottor med tydligt åtskilda axelmärken. Konvertera en daglig tidsserie till månadsvis genom att ta medeltalet under varje månad Arbeta med data som saknar värden Bestäm sista arbetsdag för föregående månadskvartal för rapporteringsändamål Beräkna en rörlig standardavvikelse effektivt Det här är bara några av de scenarier som görs mycket enkla med scikitsna . Documentation1. Språkbehandling och Python Det är lätt att ta hand om miljontals textord. Vad kan vi göra med det, förutsatt att vi kan skriva några enkla program I det här kapitlet är det bra att ta itu med följande frågor: Vad kan vi uppnå genom att kombinera enkla programmeringstekniker med stora mängder text Hur kan vi automatiskt extrahera nyckelord och fraser som sammanfattar stil och innehåll i en text Vilka verktyg och tekniker tillhandahåller Python-programmeringsspråket för sådant arbete Vad är några av de intressanta utmaningarna för naturlig språkbehandling Detta kapitel är indelat i avsnitt som hoppa över två helt olika stilar. I quotcomputing med languagequot-sektioner kommer vi att ta på sig vissa språkligt motiverade programmeringsuppgifter utan att nödvändigtvis förklara hur de fungerar. I quotclosern titta på Pythonquot-sektioner kommer vi systematiskt att granska nyckelprogrammeringskoncept. Väl flagga de två stilarna i sektionstitlarna, men senare kapitel kommer att blanda båda stilar utan att vara så uppåt om den. Vi hoppas att denna introduktionsstil ger dig en autentisk smak av vad som kommer senare, samtidigt som du täcker en rad elementära begrepp inom lingvistik och datavetenskap. Om du har grundläggande kännedom om båda områdena kan du hoppa över till 5. Vi kommer att upprepa viktiga punkter i senare kapitel, och om du saknar något kan du enkelt hämta online referensmaterialet på nltk. org. Om materialet är helt nytt för dig kommer det här kapitlet att ta upp fler frågor än det svarar, frågor som tas upp i resten av denna bok. 1 Computing with Language: Texter och ord Var alla väldigt bekanta med texten, eftersom vi läser och skriver det varje dag. Här kommer vi att behandla text som rådata för de program vi skriver, program som manipulerar och analyserar det på en mängd intressanta sätt. Men innan vi kan göra det måste vi börja med Python tolken. 1.1 Komma igång med Python En av de vänliga sakerna om Python är att det låter dig skriva direkt i den interaktiva tolken 8212 det program som kör dina Python-program. Du kan komma åt Python tolken med ett enkelt grafiskt gränssnitt som heter Interactive DeveLopment Environment (IDLE). På en Mac kan du hitta detta under Applikationer 8594 MacPython. och på Windows under Alla program 8594 Python. Under Unix kan du köra Python från skalet genom att skriva inaktiv (om det inte är installerat, försök att skriva python). Tolken skriver ut en blurb om din Python-version. Kontrollera bara att du kör Python 3.2 eller senare (här är det för 3.4.2): Första gången du använder en konkordans på en viss text, tar det några extra sekunder att bygga ett index så att efterföljande sökningar är snabba. Din tur: Försök att söka efter andra ord för att spara omskrivning, du kanske kan använda pil uppåt, Ctrl-up-pil eller Alt-p för att komma åt det föregående kommandot och ändra ordet som söks. Du kan också försöka söka på några av de andra texterna som vi har inkluderat. Till exempel, sök Sense och Sensibility för word affection. använder text2.concordance (quotaffectionquot). Sök i Genesisboken för att ta reda på hur länge vissa personer levde, med hjälp av text3.concordance (quotlivedquot). Du kan titta på text4. Inaugural Address Corpus. att se exempel på engelska som går tillbaka till 1789 och söka efter ord som nation. skräck. gud för att se hur dessa ord har använts annorlunda över tiden. Weve ingår också text5. NPS Chat Corpus. sök här efter okonventionella ord som im. UR. LOL. (Observera att det här corpuset är uncensored) När du har spenderat lite tid på att undersöka dessa texter hoppas vi att du har en ny känsla av språkets rikedom och mångfald. I nästa kapitel lär du dig tillgång till ett bredare utbud av text, inklusive text på andra språk än engelska. En överensstämmelse tillåter oss att se ord i sammanhang. Vi såg till exempel att monstrous inträffade i sammanhang som bilderna och en storlek. Vilka andra ord visas i ett liknande sammanhang Vi kan ta reda på genom att lägga till termen som liknar namnet på den aktuella texten och sedan infoga det relevanta ordet inom parentes: 2 En närmare titt på Python: Texter som ordlistor Efter snabbt weve fick ett namn vi gjorde upp, sent1. följt av lika tecken, och sedan några citerade ord, åtskilda med kommatecken och omgivna med parenteser. Detta fästmaterial är känt som en lista i Python: det är hur vi lagrar en text. Vi kan inspektera det genom att skriva namnet. Vi kan fråga om dess längd. Vi kan till och med tillämpa vår egen lexicaldiversity () funktion till den. Observera att våra index börjar från noll: skickat element noll, skrivet skickat0. är det första ordet, word1. medan skickat element 9 är word10. Orsaken är enkel: det ögonblick som Python får tillgång till innehållet i en lista från datorminnet, det är redan vid det första elementet måste vi berätta hur många element som går framåt. Således lämnar nollsteg framåt den vid det första elementet. Denna praxis att räkna från noll är initialt förvirrande men typiskt för moderna programmeringsspråk. Du kommer snabbt hänga på det om du har behärskat systemet för att räkna århundraden där 19XY är ett år på 1900-talet, eller om du bor i ett land där byggnadens våningar är numrerade från 1 och så går upp n-1 Trappsteg tar dig till nivå n. Om vi ​​av misstag använder ett index som är för stort får vi ett fel: Den här gången är det inte ett syntaxfel, eftersom programfragmentet är syntaktiskt korrekt. I stället är det ett runtime-fel. och det producerar ett Traceback-meddelande som visar felets sammanhang, följt av namnet på felet IndexError. och en kort förklaring. Låt oss titta närmare på skivning, med hjälp av vår artificiella mening igen. Här kontrollerar vi att skivan 5: 8 innehåller skickade element i index 5, 6 och 7: Vi kan ändra ett element i en lista genom att tilldela ett av dess indexvärden. I det följande exemplet sätter vi sent0 till vänster om jämliksignalen. Vi kan också ersätta en hel skiva med nytt material. En följd av den senaste ändringen är att listan endast har fyra element, och att få tillgång till ett senare värde genererar ett fel. Din tur: Ta några minuter för att definiera en mening och ändra enskilda ord och grupper av ord (skivor) med samma metoder som tidigare använts. Kontrollera din förståelse genom att försöka öva på listor i slutet av detta kapitel. 2.3 Variabler Från början av 1. har du haft tillgång till texter som heter text1. text2. och så vidare. Det räddade mycket att skriva för att kunna hänvisa till en 250 000 ordbok med ett kortnamn som detta. I allmänhet kan vi göra namnen på allt vi bryr oss att beräkna. Vi gjorde det här i de tidigare sektionerna, t. ex. definierar en variabel som skickas1. enligt följande: Sådana linjer har formen: variabelt uttryck. Python kommer att utvärdera uttrycket och spara resultatet till variabeln. Denna process kallas uppdrag. Det genererar ingen produktion du måste skriva variabeln på en rad för att inspektera dess innehåll. Liknande tecken är något vilseledande, eftersom information flyttas från höger sida till vänster. Det kan hjälpa till att tänka på det som en vänsterpil. Namnet på variabeln kan vara allt du vill, t. ex. mysent. mening . xyzzy. Det måste börja med ett brev, och det kan innehålla siffror och understreck. Här är några exempel på variabler och uppdrag: Kom ihåg att aktiverade ord visas före små bokstäver i sorterade listor. Observera i föregående exempel att vi delar upp definitionen av mysent över två linjer. Python uttryck kan delas över flera linjer, så länge som detta händer inom alla slags parenteser. Python använder citatet. quot prompt att ange att mer inmatning förväntas. Det spelar ingen roll hur mycket inryckning används i dessa fortsättningslinjer, men vissa indragningar gör det vanligtvis lättare att läsa. Det är bra att välja meningsfulla variabla namn för att påminna dig 8212 och för att hjälpa någon annan som läser din Python-kod 8212 vad din kod är tänkt att göra. Python försöker inte förnuftiga namnen, det följer blint dina anvisningar, och gör inget emot om du gör något förvirrande, till exempel en två eller två 3. Den enda begränsningen är att ett variabelt namn inte kan vara några av Pythons reserverade ord, till exempel def. om . inte och import. Om du använder ett reserverat ord kommer Python att skapa ett syntaxfel: Var försiktig med ditt val av namn (eller identifierare) för Python-variabler. Först bör du börja namnet med ett brev, valfritt följt av siffror (0 till 9) eller bokstäver. Således är abc23 bra, men 23abc kommer att orsaka ett syntaxfel. Namn är skiftlägeskänsliga, vilket betyder att myVar och myvar är olika variabler. Variable namn kan inte innehålla whitespace, men du kan skilja ord genom att använda ett understreck, t. ex. myvar. Var försiktig så att du inte sätter in en bindestreck istället för ett understreck: my-var är fel, eftersom Python tolkar citatet som ett minustecken. 2.4 Strängar Några av de metoder som vi använde för att komma åt elementen i en lista fungerar också med enskilda ord eller strängar. Till exempel kan vi tilldela en sträng till en variabel. indexera en sträng. och skiva en sträng: Vi kan också utföra multiplikation och tillägg med strängar: Vi kan ansluta sig till orden i en lista för att skapa en enda sträng, eller dela en sträng i en lista enligt följande: Vi kommer tillbaka till ämnet strängar i 3. För närvarande har vi två viktiga byggstenar 8212 listor och strängar 8212 och är redo att komma tillbaka till någon språkanalys. 3 Beräkning med språk: Enkel statistik Låt oss återgå till vår undersökning av hur vi kan få våra beräkningsresurser att bära på stora mängder text. Vi började denna diskussion i 1. och såg hur man söker efter ord i sammanhang, hur man sammanställer ordförråd i en text, hur man skapar slumpmässig text i samma stil och så vidare. I det här avsnittet tar vi upp frågan om vad som skiljer en text och använder automatiska metoder för att hitta karaktäristiska ord och uttryck för en text. Som i 1. kan du prova nya funktioner i Python-språket genom att kopiera dem till tolken, och du kommer att lära dig systematiskt om dessa funktioner i följande avsnitt. Innan du fortsätter kan du kanske kolla din förståelse av det sista avsnittet genom att förutsäga resultatet av följande kod. Du kan använda tolken för att kontrollera om du har det rätt. Om du inte är säker på hur du gör den här uppgiften, är det en bra idé att granska föregående avsnitt innan du fortsätter vidare. 3.1 Frekvensfördelningar Hur kan vi automatiskt identifiera ord i en text som är mest informativ om ämnet och genren i texten Föreställ dig hur du kan hitta om du hittar de 50 vanligaste orden i en bok. En metod skulle vara att hålla ett tal för varje ordförrådspost, som det som visas i 3.1. Tallyen skulle behöva tusentals rader, och det skulle vara en överdriven arbetskraftsprocess 8212 så jobbig att vi hellre skulle tilldela uppgiften till en maskin. Figur 3.1. Räkna ord som uppträder i en text (en frekvensfördelning) Tabellen i 3.1 kallas frekvensfördelning. och det berättar hur ofta varje ordförråd är i texten. (Generellt kan det räkna med någon form av observerbar händelse.) Det är en quotdistributionquot eftersom det berättar hur det totala antalet ordtoken i texten distribueras över ordförrådsposterna. Eftersom vi ofta behöver frekvensfördelningar i språkbehandling, erbjuder NLTK inbyggt stöd för dem. Låt oss använda en FreqDist för att hitta de 50 vanligaste orden i Moby Dick: När vi först påminner FreqDist. Vi skickar namnet på texten som ett argument. Vi kan inspektera det totala antalet ord (quotoutcomesquot) som har räknats upp 8212 260.819 i fallet Moby Dick. Uttrycket mest vanliga (50) ger oss en lista över de 50 vanligaste typerna i texten. Din tur: Försök med föregående frekvensdistributionsexempel för dig själv, för text2. Var försiktig med att använda rätt parentes och stora bokstäver. Om du får ett felmeddelande NameError: namn FreqDist är inte definierat. du behöver starta ditt arbete med från nltk. book import Gör några ord som produceras i det sista exemplet hjälpa oss att förstå ämnet eller genren i den här texten. Endast ett ord, val. är lite informativ Det sker över 900 gånger. Resten av orden berättar ingenting om texten theyre bara engelska quotplumbing. quot Vilken andel av texten tas upp med sådana ord Vi kan generera en kumulativ frekvensplott för dessa ord, med fdist1.plot (50, cumulativeTrue). för att producera grafen i 3.2. Dessa 50 ord står för nästan hälften av boken Figur 3.2. Kumulativ frekvensplan för 50 vanligaste ord i Moby Dick. Dessa står för nästan hälften av symbolerna. Om de vanliga orden inte hjälper oss, hur är det med orden som bara uppträder en gång, de så kallade hapaxerna. Visa dem genom att skriva fdist1.hapaxes (). Denna lista innehåller lexicograf. cetological. smuggelgods. expostulations. och ca 9000 andra. Det verkar som om det finns för många sällsynta ord, och utan att vi ser kontextet kan vi antagligen inte anta vad hälften av hapaxerna betyder i alla fall Eftersom varken frekventa eller sällsynta ord hjälper, behöver vi prova något annat. 3.2 Finkornigt urval av ord Nästa kan vi titta på textens långa ord kanske dessa kommer att vara mer karakteristiska och informativa. För detta anpassar vi några noteringar från uppsättningsteorin. Vi skulle vilja hitta ord från ordförrådet i texten som är längre än 15 tecken. Låt oss kalla den här egenskapen P. så att P (w) är sann om och endast om w är mer än 15 tecken långt. Nu kan vi uttrycka ord av intresse med hjälp av matematisk uppsättning notation som visas i (1a). Detta betyder quotteset av alla w så att w är ett element i V (ordförrådet) och w har egenskap P kv. Härifrån ser vi att den vanligaste ordlängden är 3, och att orden med längd 3 står för ungefär 50 000 (eller 20) av orden som utgör boken. Även om vi inte kommer att driva det här, kan ytterligare analys av ordlängd hjälpa oss att förstå skillnader mellan författare, genrer eller språk. 3.1 sammanfattar de funktioner som definieras i frekvensfördelningar. 4 Tillbaka till Python: Att fatta beslut och ta kontroll Dessa uttryck har formen f (w) för. eller w. f () för. . där f är en funktion som fungerar på ett ord för att beräkna dess längd, eller att konvertera den till stor bokstav. För nu behöver du inte förstå skillnaden mellan noteringarna f (w) och w. f (). Istället lär du bara det här Python-idiomet som utför samma funktion på alla delar av en lista. I de föregående exemplen går det igenom varje ord i text1. Tilldela var och en åt gången till variabeln w och utföra den angivna operationen på variabeln. Den beskrivna notationen kallas en quotlist comprehension. quot Detta är vårt första exempel på ett Python-idiom, en fast notation som vi använder vanligtvis utan att störa analysen varje gång. Mastering av sådana idiom är en viktig del av att bli en flytande Python programmerare. Låt oss återgå till frågan om ordförrådsstorlek och tillämpa samma idiom här: Nu när vi inte är dubbelräknande ord som This and this. som endast skiljer sig åt i kapitalisering, torkade vi 2.000 av ordförrådstalet. Vi kan gå ett steg längre och eliminera siffror och skiljetecken från ordförrådstalet genom att filtrera bort några icke-alfabetiska objekt: Detta exempel är lite komplicerat: det sänker alla rena alfabetiska objekt . Kanske hade det varit enklare att bara räkna med små bokstäver, men det ger fel svar (varför). Oroa dig inte om du inte känner dig trygg med listförståelser än, eftersom du kommer att se många fler exempel tillsammans med förklaringar i följande kapitel. 4.3 Nested Code Blocks De flesta programmeringsspråk tillåter oss att exekvera ett block av kod vid ett villkorligt uttryck. eller om uttalandet är uppfyllt. Vi har redan sett exempel på villkorliga tester i kod som w för w i sent7 om len (w) lt 4. I följande program har vi skapat en variabel som heter ord som innehåller strängvärdet katten. If-satsen kontrollerar om testlänet (word) lt 5 är sant. Det är så att omkroppsberättelsens kropp åberopas och utskriftsdeklarationen exekveras och visar ett meddelande till användaren. Kom ihåg att skriva in utskriftsutrymmet genom att skriva in fyra mellanslag. Detta kallas en loop eftersom Python exekverar koden i cirkulär mode. Det börjar med att utföra uppdragsordet Samtal. effektivt använda ordvariabeln för att namnge det första objektet i listan. Sedan visar det värdet av ordet till användaren. Därefter går det tillbaka till förklaringen och utför uppdragsordet mig. innan detta nya värde visas för användaren, och så vidare. Det fortsätter på detta sätt tills alla objekt i listan har bearbetats. 4.4 Looping with Conditions Nu kan vi kombinera om och för uttalanden. Vi kommer att slinga över varje objekt i listan och skriva ut objektet endast om det slutar med bokstaven l. Väl välj ett annat namn för variabeln för att visa att Python inte försöker få mening om variabla namn. Du kommer att märka att om och för uttalanden har ett kolon i slutet av raden innan indryckningen börjar. Faktum är att alla Python-kontrollstrukturer slutar med ett kolon. Kolon indikerar att det aktuella uttalandet avser det inramade blocket som följer. Vi kan också ange en åtgärd som ska vidtas om villkoren för if-uttalandet inte är uppfyllt. Här ser vi elif (annars om) uttalandet och det andra uttalandet. Observera att dessa också har kolon innan den indragna koden. 5 Automatisk naturligt språkförståelse Vi har undersökt språk bottom-up, med hjälp av texter och Python programmeringsspråk. Men var också intresserad av att utnyttja vår kunskap om språk och beräkning genom att bygga användbar språkteknologi. Tja, ta tillfället i akt att återgå från käften av kod för att måla en större bild av naturlig språkbehandling. På en rent praktisk nivå behöver vi alla hjälp för att navigera i universum av information som är låst i text på webben. Sökmotorer har varit avgörande för tillväxten och populariteten hos webben, men har vissa brister. Det krävs skicklighet, kunskap och lycka till att extrahera svar på sådana frågor som: Vilka turistplatser kan jag besöka mellan Philadelphia och Pittsburgh på en begränsad budget Vad säger experter om digitala SLR-kameror Vilka förutsägelser om stålmarknaden gjordes av trovärdiga kommentatorer under den senaste veckan Att få en dator att svara på dem involverar automatiskt en rad språkbehandlingsuppgifter, inklusive informationsutvinning, inferens och sammanfattning, och skulle behöva utföras på en skala och med en robusthet som fortfarande ligger utanför vår nuvarande kapacitet. På en mer filosofisk nivå har en långvarig utmaning inom artificiell intelligens varit att bygga intelligenta maskiner, och en stor del av det intelligenta beteendet är förståelse för språket. I många år har detta mål uppfattats som för svårt. Men eftersom NLP-tekniken blir mogen och robusta metoder för att analysera obegränsad text blir mer utbredd, har utsikterna till naturlig språkförståelse åter uppstått som ett trovärdigt mål. I det här avsnittet beskriver vi en del språkkunnande tekniker för att ge dig en känsla av de intressanta utmaningar som väntar på dig. 5.1 Word-sense-disambiguering I ordsinne-skiljedom vill vi utreda vilken känsla av ett ord som var tänkt i ett visst sammanhang. Tänk på de tvetydiga orden servera och maträtt: servera. hjälp med mat eller dryck håll ett kontor placera bollen i spelrätten. Plattformen av en måltidskommunikationsanordning I en mening som innehöll frasen: han serverade skålen. du kan upptäcka att både servering och maträtt används med deras betydelse för maten. Det är osannolikt att diskussionsämnet flyttas från sport till porslin i tre ord. Detta skulle tvinga dig att uppfinna bisarra bilder, som om en tennisprofför tar ut sina frustrationer på en kinesisk te-uppsättning som läggs ut bredvid domstolen. Med andra ord automatiserar vi automatiskt ord med hjälp av sammanhang och utnyttjar det enkla faktumet att närstående ord har nära relaterade betydelser. Som ett annat exempel på denna kontextuella effekt, överväga ordet av. som har flera betydelser, t. ex. boken från Chesterton (agent 8212 Chesterton var bokens författare) bägaren vid kaminen (lokal 8212, kaminen är där bägaren är) och skickar in till fredag ​​(tidsmässigt 8212 fredag ​​är inlämningstiden). Observera i (3c) att meningen med det kursiverade ordet hjälper oss att tolka betydelsen av. De förlorade barnen hittades av sökarna (agentiska) De förlorade barnen hittades av berget (lokal) De förlorade barnen hittades på eftermiddagen (temporal) 5.2 Pronoun Resolution En djupare typ av språkförståelse är att utarbeta kvoten som gjorde vad whoquot 8212 dvs att upptäcka ämnen och objekt av verb. Du lärde dig att göra detta i grundskolan, men det är svårare än du kanske tror. I satsen stal tjuvarna målningarna det är lätt att berätta för vem som utförde stjälningen. Tänk på tre möjliga följande meningar i (4c). och försök att bestämma vad som såldes, fångats och hittades (ett fall är tvetydigt). Tjuvarna stal målningarna. De såldes därefter. Tjuvarna stal målningarna. De fångades därefter. Tjuvarna stal målningarna. De hittades sedan. Att svara på den här frågan innebär att man finner pronomen som föregångare. antingen tjuvar eller målningar. Beräkningstekniker för att ta itu med detta problem inkluderar anaphorupplösning 8212 som identifierar vad en pronomen eller substantivfras hänvisar till 8212 och semantisk rollmärkning 8212 identifierar hur en substantivfras relaterar till verbet (som agent, patient, instrument, och så vidare). 5.3 Generera språkutmatning Om vi ​​automatiskt kan lösa sådana problem med språkförståelse, kan vi gå vidare till uppgifter som innebär att man genererar språkutmatning, till exempel frågor som svarar på frågor och maskinöversättning. I det första fallet bör en maskin kunna svara på användarnas frågor om insamling av texter: För att avgöra om hypotesen stöds av texten behöver systemet följande bakgrundskunskaper: (i) om någon är en författare av en bok, då har heshe skrivit den boken (ii) om någon är redaktör för en bok, så har heshe inte skrivit (hela) den boken (iii) om någon är redaktör eller författare till arton böcker, kan man inte dra slutsatsen den heshe är författare till arton böcker. 5.7 Begränsningar av NLP Trots de forskningsinriktade framstegen i uppgifter som RTE har naturliga språksystem som har implementerats för verkliga applikationer fortfarande inte kunnat göra resonemang för rätthet eller dra på sig världskunskap på ett allmänt och robust sätt. Vi kan vänta på att dessa svåra problem med artificiell intelligens löses, men under tiden är det nödvändigt att leva med vissa allvarliga begränsningar av naturliga språksystems resonemang och kunskapsförmåga. Följaktligen har ett viktigt mål med NLP-forskning precis varit från början att göra framsteg på den svåra uppgiften att bygga teknik som kvitterar språk, citerar ytliga men kraftfulla tekniker i stället för obegränsad kunskap och resonemang. Detta är verkligen ett av målen i den här boken, och vi hoppas att utrusta dig med kunskap och färdigheter för att bygga användbara NLP-system och bidra till den långsiktiga ambitionen att bygga intelligenta maskiner. Texter är representerade i Python med hjälp av listor: Monty. Python. Vi kan använda indexering, skivning och funktionen len () på listor. Ett ord quottokenquot är ett visst utseende av ett givet ord i en text ett ord quottypequot är den unika formen av ordet som en viss bokstavsordning. Vi räknar ordet tokens med hjälp av len (text) och ordtyper med len (set (text)). Vi får ordförråd av en text t med hjälp av sorterade (set (t)). Vi arbetar på varje objekt i en text med f (x) för x i text. För att härleda vokabuläret, kollapsande fallskillnader och ignorering av skiljetecken kan vi skriva set (w. lower () för w i text om w. isalpha ()). Vi bearbetar varje ord i en text med hjälp av ett för uttalande, till exempel för w i t: eller för ord i text:. Detta måste följas av kolontecknet och ett inmatat block av kod som ska utföras varje gång genom slingan. Vi testar ett tillstånd med ett if-uttalande: om len (word) lt 5:. Detta måste följas av kolontecknet och ett inmatat block av kod, som endast ska utföras om villkoret är sant. En frekvensfördelning är en samling av objekt tillsammans med deras frekvensantal (t ex ord av en text och deras frekvens av utseende). En funktion är ett block av kod som har fått ett namn och kan återanvändas. Funktioner definieras med hjälp av def-nyckelordet, som i def mult (x, y) x och y är parametrar för funktionen och fungerar som platshållare för faktiska datavärden. En funktion kallas genom att ange sitt namn följt av noll eller flera argument inom parentes, så här: texter (). mult (3, 4). len (text1). 7 Ytterligare läsning Det här kapitlet har introducerat nya begrepp inom programmering, naturligt språkbearbetning och lingvistik, alla blandade ihop. Många av dem konsolideras i följande kapitel. Du kan emellertid också vilja se online materialet som tillhandahålls i detta kapitel (på nltk. org), inklusive länkar till ytterligare bakgrundsmaterial och länkar till NLP-system online. Du kanske också gillar att läsa om några lingvistik och NLP-relaterade begrepp i Wikipedia (t ex samlokaliseringar, Turing-testet, typtoken-skillnaden). Du bör bekanta dig med Python-dokumentationen tillgänglig på docs. python. org. inklusive de många handledningarna och omfattande referensmaterial som är länkade där. En nybörjarguide till Python finns på wiki. python. orgmoinBeginnersGuide. Diverse frågor om Python kan besvaras i FAQ på python. orgdocfaqgeneral. När du gräver in i NLTK, kanske du vill prenumerera på e-postlistan där nya utgåvor av verktygslådan meddelas. Det finns också en NLTK-användare-postlista där användarna hjälper varandra, eftersom de lär sig att använda Python och NLTK för språkanalysarbete. Detaljer om dessa listor finns på nltk. org. För mer information om de ämnen som omfattas av 5. och på NLP mer generellt kan du kanske höra en av följande utmärkta böcker: Indurkhya, Nitin och Fred Damerau (eds, 2010) Handbok för naturlig språkbehandling (andra upplagan) Chapman amp HallCRC. 2010. (Indurkhya amp Damerau, 2010) (Dale, Moisl, amp Somers, 2000) Jurafsky, Daniel och James Martin (2008) Tal - och språkbehandling (andra upplagan). Prentice Hall. (Jurafsky amp Martin, 2008) Mitkov, Ruslan (ed, 2003) Oxford Handbook of Computational Linguistics. Oxford University Press. (andra upplagan förväntas 2010). (Mitkov, 2002) Association for Computational Linguistics är den internationella organisationen som representerar NLP. ACL-webbplatsen (aclweb. org) är värd för många användbara resurser, bland annat: information om internationella och regionala konferenser och workshops ACL Wiki med länkar till hundratals användbara resurser och ACL Anthology. som innehåller de flesta NLP-forskningslitteraturen från de senaste 50 åren, helt indexerade och fritt nedladdningsbara. Några utmärkta inledande språkböcker är: Finegan2007. (OGrady et al, 2004). (OSU, 2007). Du kanske gillar att konsultera LanguageLog. en populär lingvistikblogg med tillfälliga inlägg som använder de tekniker som beskrivs i den här boken. 8 Övningar 9788 Försök använda Python tolken som en räknare och skriv uttryck som 12 (4 1). 9788 Med ett alfabet med 26 bokstäver finns 26 till effekten 10 eller 26 10. tio bokstäver vi kan bilda. Det fungerar till 141167095653376. Hur många hundra bokstäver är möjliga 9788 Python-multiplikationsoperationen kan appliceras på listor. Vad händer när du skriver Monty. Python 20. eller 3 sent1 9788 Granska 1 om beräkning med språk. Hur många ord finns det i text2. Hur många distinkta ord finns det? 9788 Jämför de lexiska mångfalden för humor och romansfiktion i 1.1. Vilken genre är mer lexiskt olik 9788 Skapa en dispersionsdiagram av de fyra huvudpersonerna i Sense och Sensibility. Elinor, Marianne, Edward och Willoughby. Vad kan du observera om de olika rollerna som män och kvinnor spelar i den här novellen Kan du identifiera paren 9788 Hitta collocationsna i text5. 9788 Tänk på följande Python-uttryck: len (set (text4)). Ange syftet med detta uttryck. Beskriv de två stegen som är involverade i utförandet av denna beräkning. 9788 Recension 2 på listor och strängar. Definiera en sträng och tilldela den till en variabel, t. ex. mystring My String (men sätta något mer intressant i strängen). Skriv ut innehållet i den här variabeln på två sätt, först genom att bara skriva variabelnamnet och trycka på enter, sedan genom att använda utskriftsdeklarationen. Prova att lägga till strängen till sig själv med mystring mystring. eller multiplicera det med ett tal, t. ex. mystring 3. Observera att strängarna är sammanfogade utan några mellanslag. Hur kan du fixa detta 9788 Definiera en variabel mysent för att vara en lista med ord, med hjälp av syntaxen mysent quotMyquot. quotsentquot (men med egna ord eller ett favoritordstäv). Använd. join (mysent) för att konvertera detta till en sträng. Använd split () för att dela strängen tillbaka i listformen du måste börja med. 9788 Definiera flera variabler som innehåller listor med ord, t. ex. fras1. fras2. och så vidare. Sammanfoga dem i olika kombinationer (med plus-operatören) för att bilda hela meningar. Vad är förhållandet mellan len (fras 1 fras2) och len (fras1) len (fras2) 9788 Tänk på följande två uttryck, som har samma värde. Which one will typically be more relevant in NLP Why 9788 We have seen how to represent a sentence as a list of words, where each word is a sequence of characters. What does sent122 do Why Experiment with other index values. 9788 The first sentence of text3 is provided to you in the variable sent3 . The index of the in sent3 is 1, because sent31 gives us the . What are the indexes of the two other occurrences of this word in sent3 9788 Review the discussion of conditionals in 4. Find all words in the Chat Corpus ( text5 ) starting with the letter b. Show them in alphabetical order. 9788 Type the expression list(range(10)) at the interpreter prompt. Now try list(range(10, 20)) . list(range(10, 20, 2)) . and list(range(20, 10, -2)) . We will see a variety of uses for this built-in function in later chapters. 9681 Use text9.index() to find the index of the word sunset. Youll need to insert this word as an argument between the parentheses. By a process of trial and error, find the slice for the complete sentence that contains this word. 9681 Using list addition, and the set and sorted operations, compute the vocabulary of the sentences sent1 . sent8 . 9681 What is the difference between the following two lines Which one will give a larger value Will this be the case for other texts Docutils System Messages1 Language Processing and Python It is easy to get our hands on millions of words of text. What can we do with it, assuming we can write some simple programs In this chapter well address the following questions: What can we achieve by combining simple programming techniques with large quantities of text How can we automatically extract key words and phrases that sum up the style and content of a text What tools and techniques does the Python programming language provide for such work What are some of the interesting challenges of natural language processing This chapter is divided into sections that skip between two quite different styles. In the quotcomputing with languagequot sections we will take on some linguistically motivated programming tasks without necessarily explaining how they work. In the quotcloser look at Pythonquot sections we will systematically review key programming concepts. Well flag the two styles in the section titles, but later chapters will mix both styles without being so up-front about it. We hope this style of introduction gives you an authentic taste of what will come later, while covering a range of elementary concepts in linguistics and computer science. If you have basic familiarity with both areas, you can skip to 1.5 we will repeat any important points in later chapters, and if you miss anything you can easily consult the online reference material at nltk. org . If the material is completely new to you, this chapter will raise more questions than it answers, questions that are addressed in the rest of this book. 1.1 Computing with Language: Texts and Words Were all very familiar with text, since we read and write it every day. Here we will treat text as raw data for the programs we write, programs that manipulate and analyze it in a variety of interesting ways. But before we can do this, we have to get started with the Python interpreter. Getting Started with Python One of the friendly things about Python is that it allows you to type directly into the interactive interpreter 8212 the program that will be running your Python programs. You can access the Python interpreter using a simple graphical interface called the Interactive DeveLopment Environment (IDLE). On a Mac you can find this under Applications 8594 MacPython . and on Windows under All Programs 8594 Python . Under Unix you can run Python from the shell by typing idle (if this is not installed, try typing python ). The interpreter will print a blurb about your Python version simply check that you are running Python 2.4 or 2.5 (here it is 2.5.1): Your Turn: Try searching for other words to save re-typing, you might be able to use up-arrow, Ctrl-up-arrow or Alt-p to access the previous command and modify the word being searched. You can also try searches on some of the other texts we have included. For example, search Sense and Sensibility for the word affection. using text2.concordance( quotaffectionquot ) . Search the book of Genesis to find out how long some people lived, using text3.concordance( quotlivedquot ) . You could look at text4 . the Inaugural Address Corpus . to see examples of English going back to 1789, and search for words like nation. terror. god to see how these words have been used differently over time. Weve also included text5 . the NPS Chat Corpus . search this for unconventional words like im. ur. lol. (Note that this corpus is uncensored) Once youve spent a little while examining these texts, we hope you have a new sense of the richness and diversity of language. In the next chapter you will learn how to access a broader range of text, including text in languages other than English. A concordance permits us to see words in context. For example, we saw that monstrous occurred in contexts such as the pictures and the size. What other words appear in a similar range of contexts We can find out by appending the term similar to the name of the text in question, then inserting the relevant word in parentheses: Observe that we get different results for different texts. Austen uses this word quite differently from Melville for her, monstrous has positive connotations, and sometimes functions as an intensifier like the word very . The term commoncontexts allows us to examine just the contexts that are shared by two or more words, such as monstrous and very. We have to enclose these words by square brackets as well as parentheses, and separate them with a comma: Your Turn: Pick another pair of words and compare their usage in two different texts, using the similar() and commoncontexts() functions. It is one thing to automatically detect that a particular word occurs in a text, and to display some words that appear in the same context. However, we can also determine the location of a word in the text: how many words from the beginning it appears. This positional information can be displayed using a dispersion plot. Each stripe represents an instance of a word, and each row represents the entire text. In 1.2 we see some striking patterns of word usage over the last 220 years (in an artificial text constructed by joining the texts of the Inaugural Address Corpus end-to-end). You can produce this plot as shown below. You might like to try more words (e. g. liberty. constitution ), and different texts. Can you predict the dispersion of a word before you view it As before, take care to get the quotes, commas, brackets and parentheses exactly right. Figure 1.2. Lexical Dispersion Plot for Words in U. S. Presidential Inaugural Addresses: This can be used to investigate changes in language use over time. Important: You need to have Pythons NumPy and Matplotlib packages installed in order to produce the graphical plots used in this book. Please see nltk. org for installation instructions. Now, just for fun, lets try generating some random text in the various styles we have just seen. To do this, we type the name of the text followed by the term generate . (We need to include the parentheses, but theres nothing that goes between them.) Note that the first time you run this command, it is slow because it gathers statistics about word sequences. Each time you run it, you will get different output text. Now try generating random text in the style of an inaugural address or an Internet chat room. Although the text is random, it re-uses common words and phrases from the source text and gives us a sense of its style and content. (What is lacking in this randomly generated text) When generate produces its output, punctuation is split off from the preceding word. While this is not correct formatting for English text, we do it to make clear that words and punctuation are independent of one another. You will learn more about this in 3 . Counting Vocabulary The most obvious fact about texts that emerges from the preceding examples is that they differ in the vocabulary they use. In this section we will see how to use the computer to count the words in a text in a variety of useful ways. As before, you will jump right in and experiment with the Python interpreter, even though you may not have studied Python systematically yet. Test your understanding by modifying the examples, and trying the exercises at the end of the chapter. Lets begin by finding out the length of a text from start to finish, in terms of the words and punctuation symbols that appear. We use the term len to get the length of something, which well apply here to the book of Genesis: So Genesis has 44,764 words and punctuation symbols, or quottokens. quot A token is the technical name for a sequence of characters 8212 such as hairy . his . or :) 8212 that we want to treat as a group. When we count the number of tokens in a text, say, the phrase to be or not to be. we are counting occurrences of these sequences. Thus, in our example phrase there are two occurrences of to. two of be. and one each of or and not. But there are only four distinct vocabulary items in this phrase. How many distinct words does the book of Genesis contain To work this out in Python, we have to pose the question slightly differently. The vocabulary of a text is just the set of tokens that it uses, since in a set, all duplicates are collapsed together. In Python we can obtain the vocabulary items of text3 with the command: set(text3) . When you do this, many screens of words will fly past. Now try the following: By wrapping sorted() around the Python expression set(text3) . we obtain a sorted list of vocabulary items, beginning with various punctuation symbols and continuing with words starting with A. All capitalized words precede lowercase words. We discover the size of the vocabulary indirectly, by asking for the number of items in the set, and again we can use len to obtain this number . Although it has 44,764 tokens, this book has only 2,789 distinct words, or quotword types. quot A word type is the form or spelling of the word independently of its specific occurrences in a text 8212 that is, the word considered as a unique item of vocabulary. Our count of 2,789 items will include punctuation symbols, so we will generally call these unique items types instead of word types. Now, lets calculate a measure of the lexical richness of the text. The next example shows us that each word is used 16 times on average (we need to make sure Python uses floating point division): Notice that our indexes start from zero: sent element zero, written sent0 . is the first word, word1 . whereas sent element 9 is word10 . The reason is simple: the moment Python accesses the content of a list from the computers memory, it is already at the first element we have to tell it how many elements forward to go. Thus, zero steps forward leaves it at the first element. This practice of counting from zero is initially confusing, but typical of modern programming languages. Youll quickly get the hang of it if youve mastered the system of counting centuries where 19XY is a year in the 20th century, or if you live in a country where the floors of a building are numbered from 1, and so walking up n-1 flights of stairs takes you to level n . Now, if we accidentally use an index that is too large, we get an error: This time it is not a syntax error, because the program fragment is syntactically correct. Instead, it is a runtime error. and it produces a Traceback message that shows the context of the error, followed by the name of the error, IndexError . and a brief explanation. Lets take a closer look at slicing, using our artificial sentence again. Here we verify that the slice 5:8 includes sent elements at indexes 5, 6, and 7: We can modify an element of a list by assigning to one of its index values. In the next example, we put sent0 on the left of the equals sign . We can also replace an entire slice with new material . A consequence of this last change is that the list only has four elements, and accessing a later value generates an error . Your Turn: Take a few minutes to define a sentence of your own and modify individual words and groups of words (slices) using the same methods used earlier. Check your understanding by trying the exercises on lists at the end of this chapter. From the start of 1.1. you have had access to texts called text1 . text2 . och så vidare. It saved a lot of typing to be able to refer to a 250,000-word book with a short name like this In general, we can make up names for anything we care to calculate. We did this ourselves in the previous sections, e. g. defining a variable sent1 . as follows: Such lines have the form: variable expression . Python will evaluate the expression, and save its result to the variable. This process is called assignment. It does not generate any output you have to type the variable on a line of its own to inspect its contents. The equals sign is slightly misleading, since information is moving from the right side to the left. It might help to think of it as a left-arrow. The name of the variable can be anything you like, e. g. mysent . sentence . xyzzy . It must start with a letter, and can include numbers and underscores. Here are some examples of variables and assignments: Remember that capitalized words appear before lowercase words in sorted lists. Notice in the previous example that we split the definition of mysent over two lines. Python expressions can be split across multiple lines, so long as this happens within any kind of brackets. Python uses the quot . quot prompt to indicate that more input is expected. It doesnt matter how much indentation is used in these continuation lines, but some indentation usually makes them easier to read. It is good to choose meaningful variable names to remind you 8212 and to help anyone else who reads your Python code 8212 what your code is meant to do. Python does not try to make sense of the names it blindly follows your instructions, and does not object if you do something confusing, such as one two or two 3 . The only restriction is that a variable name cannot be any of Pythons reserved words, such as def . if . not . and import . If you use a reserved word, Python will produce a syntax error: Take care with your choice of names (or identifiers ) for Python variables. First, you should start the name with a letter, optionally followed by digits ( 0 to 9 ) or letters. Thus, abc23 is fine, but 23abc will cause a syntax error. Names are case-sensitive, which means that myVar and myvar are distinct variables. Variable names cannot contain whitespace, but you can separate words using an underscore, e. g. myvar . Be careful not to insert a hyphen instead of an underscore: my-var is wrong, since Python interprets the quot - quot as a minus sign. Some of the methods we used to access the elements of a list also work with individual words, or strings. For example, we can assign a string to a variable . index a string . and slice a string : We can also perform multiplication and addition with strings: We can join the words of a list to make a single string, or split a string into a list, as follows: We will come back to the topic of strings in 3. For the time being, we have two important building blocks 8212 lists and strings 8212 and are ready to get back to some language analysis. 1.3 Computing with Language: Simple Statistics Lets return to our exploration of the ways we can bring our computational resources to bear on large quantities of text. We began this discussion in 1.1. and saw how to search for words in context, how to compile the vocabulary of a text, how to generate random text in the same style, and so on. In this section we pick up the question of what makes a text distinct, and use automatic methods to find characteristic words and expressions of a text. As in 1.1. you can try new features of the Python language by copying them into the interpreter, and youll learn about these features systematically in the following section. Before continuing further, you might like to check your understanding of the last section by predicting the output of the following code. You can use the interpreter to check whether you got it right. If youre not sure how to do this task, it would be a good idea to review the previous section before continuing further. Frequency Distributions How can we automatically identify the words of a text that are most informative about the topic and genre of the text Imagine how you might go about finding the 50 most frequent words of a book. One method would be to keep a tally for each vocabulary item, like that shown in 1.3. The tally would need thousands of rows, and it would be an exceedingly laborious process 8212 so laborious that we would rather assign the task to a machine. Figure 1.3. Counting Words Appearing in a Text (a frequency distribution) The table in 1.3 is known as a frequency distribution. and it tells us the frequency of each vocabulary item in the text. (In general, it could count any kind of observable event.) It is a quotdistributionquot because it tells us how the total number of word tokens in the text are distributed across the vocabulary items. Since we often need frequency distributions in language processing, NLTK provides built-in support for them. Lets use a FreqDist to find the 50 most frequent words of Moby Dick . Try to work out what is going on here, then read the explanation that follows. When we first invoke FreqDist . we pass the name of the text as an argument . We can inspect the total number of words (quotoutcomesquot) that have been counted up 8212 260,819 in the case of Moby Dick . The expression keys () gives us a list of all the distinct types in the text . and we can look at the first 50 of these by slicing the list . Your Turn: Try the preceding frequency distribution example for yourself, for text2 . Be careful to use the correct parentheses and uppercase letters. If you get an error message NameError: name FreqDist is not defined . you need to start your work with from nltk. book import Do any words produced in the last example help us grasp the topic or genre of this text Only one word, whale. is slightly informative It occurs over 900 times. The rest of the words tell us nothing about the text theyre just English quotplumbing. quot What proportion of the text is taken up with such words We can generate a cumulative frequency plot for these words, using fdist1.plot(50, cumulativeTrue) . to produce the graph in 1.4. These 50 words account for nearly half the book Figure 1.4. Cumulative Frequency Plot for 50 Most Frequently Words in Moby Dick . these account for nearly half of the tokens. If the frequent words dont help us, how about the words that occur once only, the so-called hapaxes. View them by typing fdist1.hapaxes() . This list contains lexicographer. cetological. contraband. expostulations. and about 9,000 others. It seems that there are too many rare words, and without seeing the context we probably cant guess what half of the hapaxes mean in any case Since neither frequent nor infrequent words help, we need to try something else. Fine-grained Selection of Words Next, lets look at the long words of a text perhaps these will be more characteristic and informative. For this we adapt some notation from set theory. We would like to find the words from the vocabulary of the text that are more than 15 characters long. Lets call this property P. so that P(w) is true if and only if w is more than 15 characters long. Now we can express the words of interest using mathematical set notation as shown in (1a). This means quotthe set of all w such that w is an element of V (the vocabulary) and w has property P quot. From this we see that the most frequent word length is 3, and that words of length 3 account for roughly 50,000 (or 20) of the words making up the book. Although we will not pursue it here, further analysis of word length might help us understand differences between authors, genres, or languages. 1.2 summarizes the functions defined in frequency distributions. These expressions have the form f(w) for. or w. f() for. . where f is a function that operates on a word to compute its length, or to convert it to uppercase. For now, you dont need to understand the difference between the notations f(w) and w. f() . Instead, simply learn this Python idiom which performs the same operation on every element of a list. In the preceding examples, it goes through each word in text1 . assigning each one in turn to the variable w and performing the specified operation on the variable. The notation just described is called a quotlist comprehension. quot This is our first example of a Python idiom, a fixed notation that we use habitually without bothering to analyze each time. Mastering such idioms is an important part of becoming a fluent Python programmer. Lets return to the question of vocabulary size, and apply the same idiom here: Now that we are not double-counting words like This and this. which differ only in capitalization, weve wiped 2,000 off the vocabulary count We can go a step further and eliminate numbers and punctuation from the vocabulary count by filtering out any non-alphabetic items: This example is slightly complicated: it lowercases all the purely alphabetic items. Perhaps it would have been simpler just to count the lowercase-only items, but this gives the wrong answer (why). Dont worry if you dont feel confident with list comprehensions yet, since youll see many more examples along with explanations in the following chapters. Nested Code Blocks Most programming languages permit us to execute a block of code when a conditional expression. or if statement, is satisfied. We already saw examples of conditional tests in code like w for w in sent7 if len(w) lt 4 . In the following program, we have created a variable called word containing the string value cat . The if statement checks whether the test len(word) lt 5 is true. It is, so the body of the if statement is invoked and the print statement is executed, displaying a message to the user. Remember to indent the print statement by typing four spaces. This is called a loop because Python executes the code in circular fashion. It starts by performing the assignment word Call . effectively using the word variable to name the first item of the list. Then, it displays the value of word to the user. Next, it goes back to the for statement, and performs the assignment word me . before displaying this new value to the user, and so on. It continues in this fashion until every item of the list has been processed. Looping with Conditions Now we can combine the if and for statements. We will loop over every item of the list, and print the item only if it ends with the letter l . Well pick another name for the variable to demonstrate that Python doesnt try to make sense of variable names. You will notice that if and for statements have a colon at the end of the line, before the indentation begins. In fact, all Python control structures end with a colon. The colon indicates that the current statement relates to the indented block that follows. We can also specify an action to be taken if the condition of the if statement is not met. Here we see the elif (else if) statement, and the else statement. Notice that these also have colons before the indented code. 1.5 Automatic Natural Language Understanding We have been exploring language bottom-up, with the help of texts and the Python programming language. However, were also interested in exploiting our knowledge of language and computation by building useful language technologies. Well take the opportunity now to step back from the nitty-gritty of code in order to paint a bigger picture of natural language processing. At a purely practical level, we all need help to navigate the universe of information locked up in text on the Web. Search engines have been crucial to the growth and popularity of the Web, but have some shortcomings. It takes skill, knowledge, and some luck, to extract answers to such questions as: What tourist sites can I visit between Philadelphia and Pittsburgh on a limited budget What do experts say about digital SLR cameras What predictions about the steel market were made by credible commentators in the past week Getting a computer to answer them automatically involves a range of language processing tasks, including information extraction, inference, and summarization, and would need to be carried out on a scale and with a level of robustness that is still beyond our current capabilities. On a more philosophical level, a long-standing challenge within artificial intelligence has been to build intelligent machines, and a major part of intelligent behaviour is understanding language. For many years this goal has been seen as too difficult. However, as NLP technologies become more mature, and robust methods for analyzing unrestricted text become more widespread, the prospect of natural language understanding has re-emerged as a plausible goal. In this section we describe some language understanding technologies, to give you a sense of the interesting challenges that are waiting for you. Word Sense Disambiguation In word sense disambiguation we want to work out which sense of a word was intended in a given context. Consider the ambiguous words serve and dish : serve. help with food or drink hold an office put ball into play dish. plate course of a meal communications device In a sentence containing the phrase: he served the dish. you can detect that both serve and dish are being used with their food meanings. Its unlikely that the topic of discussion shifted from sports to crockery in the space of three words. This would force you to invent bizarre images, like a tennis pro taking out their frustrations on a china tea-set laid out beside the court. In other words, we automatically disambiguate words using context, exploiting the simple fact that nearby words have closely related meanings. As another example of this contextual effect, consider the word by. which has several meanings, e. g. the book by Chesterton (agentive 8212 Chesterton was the author of the book) the cup by the stove (locative 8212 the stove is where the cup is) and submit by Friday (temporal 8212 Friday is the time of the submitting). Observe in (3c) that the meaning of the italicized word helps us interpret the meaning of by . The lost children were found by the searchers (agentive) The lost children were found by the mountain (locative) The lost children were found by the afternoon (temporal) Pronoun Resolution A deeper kind of language understanding is to work out quotwho did what to whomquot 8212 i. e. to detect the subjects and objects of verbs. You learnt to do this in elementary school, but its harder than you might think. In the sentence the thieves stole the paintings it is easy to tell who performed the stealing action. Consider three possible following sentences in (4c). and try to determine what was sold, caught, and found (one case is ambiguous). The thieves stole the paintings. They were subsequently sold . The thieves stole the paintings. They were subsequently caught . The thieves stole the paintings. They were subsequently found . Answering this question involves finding the antecedent of the pronoun they. either thieves or paintings. Computational techniques for tackling this problem include anaphora resolution 8212 identifying what a pronoun or noun phrase refers to 8212 and semantic role labeling 8212 identifying how a noun phrase relates to the verb (as agent, patient, instrument, and so on). Generating Language Output If we can automatically solve such problems of language understanding, we will be able to move on to tasks that involve generating language output, such as question answering and machine translation. In the first case, a machine should be able to answer a users questions relating to collection of texts: In order to determine whether the hypothesis is supported by the text, the system needs the following background knowledge: (i) if someone is an author of a book, then heshe has written that book (ii) if someone is an editor of a book, then heshe has not written (all of) that book (iii) if someone is editor or author of eighteen books, then one cannot conclude that heshe is author of eighteen books. Limitations of NLP Despite the research-led advances in tasks like RTE, natural language systems that have been deployed for real-world applications still cannot perform common-sense reasoning or draw on world knowledge in a general and robust manner. We can wait for these difficult artificial intelligence problems to be solved, but in the meantime it is necessary to live with some severe limitations on the reasoning and knowledge capabilities of natural language systems. Accordingly, right from the beginning, an important goal of NLP research has been to make progress on the difficult task of building technologies that quotunderstand language, quot using superficial yet powerful techniques instead of unrestricted knowledge and reasoning capabilities. Indeed, this is one of the goals of this book, and we hope to equip you with the knowledge and skills to build useful NLP systems, and to contribute to the long-term aspiration of building intelligent machines. 1.6 Summary Texts are represented in Python using lists: Monty. Python . We can use indexing, slicing, and the len() function on lists. A word quottokenquot is a particular appearance of a given word in a text a word quottypequot is the unique form of the word as a particular sequence of letters. We count word tokens using len(text) and word types using len(set(text)) . We obtain the vocabulary of a text t using sorted(set(t)) . We operate on each item of a text using f(x) for x in text . To derive the vocabulary, collapsing case distinctions and ignoring punctuation, we can write set(w. lower() for w in text if w. isalpha()) . We process each word in a text using a for statement, such as for w in t: or for word in text: . This must be followed by the colon character and an indented block of code, to be executed each time through the loop. We test a condition using an if statement: if len(word) lt 5: . This must be followed by the colon character and an indented block of code, to be executed only if the condition is true. A frequency distribution is a collection of items along with their frequency counts (e. g. the words of a text and their frequency of appearance). A function is a block of code that has been assigned a name and can be reused. Functions are defined using the def keyword, as in def mult (x, y) x and y are parameters of the function, and act as placeholders for actual data values. A function is called by specifying its name followed by one or more arguments inside parentheses, like this: mult(3, 4) . t. ex. len(text1) . 1.7 Further Reading This chapter has introduced new concepts in programming, natural language processing, and linguistics, all mixed in together. Many of them are consolidated in the following chapters. However, you may also want to consult the online materials provided with this chapter (at nltk. org ), including links to additional background materials, and links to online NLP systems. You may also like to read up on some linguistics and NLP-related concepts in Wikipedia (e. g. collocations, the Turing Test, the type-token distinction). You should acquaint yourself with the Python documentation available at docs. python. org . including the many tutorials and comprehensive reference materials linked there. A Beginners Guide to Python is available at wiki. python. orgmoinBeginnersGuide . Miscellaneous questions about Python might be answered in the FAQ at python. orgdocfaqgeneral . As you delve into NLTK, you might want to subscribe to the mailing list where new releases of the toolkit are announced. There is also an NLTK-Users mailing list, where users help each other as they learn how to use Python and NLTK for language analysis work. Details of these lists are available at nltk. org . For more information on the topics covered in 1.5. and on NLP more generally, you might like to consult one of the following excellent books: Indurkhya, Nitin and Fred Damerau (eds, 2010) Handbook of Natural Language Processing (Second Edition) Chapman amp HallCRC. 2010. (Indurkhya amp Damerau, 2010) (Dale, Moisl, amp Somers, 2000) Jurafsky, Daniel and James Martin (2008) Speech and Language Processing (Second Edition). Prentice Hall. (Jurafsky amp Martin, 2008) Mitkov, Ruslan (ed, 2003) The Oxford Handbook of Computational Linguistics . Oxford University Press. (second edition expected in 2010). (Mitkov, 2002) The Association for Computational Linguistics is the international organization that represents the field of NLP. The ACL website ( aclweb. org ) hosts many useful resources, including: information about international and regional conferences and workshops the ACL Wiki with links to hundreds of useful resources and the ACL Anthology. which contains most of the NLP research literature from the past 50 years, fully indexed and freely downloadable. Some excellent introductory Linguistics textbooks are: (Finegan, 2007). (OGrady et al, 2004). (OSU, 2007). You might like to consult LanguageLog. a popular linguistics blog with occasional posts that use the techniques described in this book. 1.8 Exercises 9788 Try using the Python interpreter as a calculator, and typing expressions like 12 (4 1) . 9788 Given an alphabet of 26 letters, there are 26 to the power 10, or 26 10 . ten-letter strings we can form. That works out to 141167095653376L (the L at the end just indicates that this is Pythons long-number format). How many hundred-letter strings are possible 9788 The Python multiplication operation can be applied to lists. What happens when you type Monty. Python 20 . or 3 sent1 9788 Review 1.1 on computing with language. How many words are there in text2 . How many distinct words are there 9788 Compare the lexical diversity scores for humor and romance fiction in 1.1. Which genre is more lexically diverse 9788 Produce a dispersion plot of the four main protagonists in Sense and Sensibility . Elinor, Marianne, Edward, and Willoughby. What can you observe about the different roles played by the males and females in this novel Can you identify the couples 9788 Find the collocations in text5 . 9788 Consider the following Python expression: len(set(text4)) . State the purpose of this expression. Describe the two steps involved in performing this computation. 9788 Review 1.2 on lists and strings. Define a string and assign it to a variable, e. g. mystring My String (but put something more interesting in the string). Print the contents of this variable in two ways, first by simply typing the variable name and pressing enter, then by using the print statement. Try adding the string to itself using mystring mystring . or multiplying it by a number, e. g. mystring 3 . Notice that the strings are joined together without any spaces. How could you fix this 9788 Define a variable mysent to be a list of words, using the syntax mysent quotMyquot. quotsentquot (but with your own words, or a favorite saying). Use. join(mysent) to convert this into a string. Use split() to split the string back into the list form you had to start with. 9788 Define several variables containing lists of words, e. g. phrase1 . phrase2 . och så vidare. Join them together in various combinations (using the plus operator) to form whole sentences. What is the relationship between len(phrase1 phrase2) and len(phrase1) len(phrase2) 9788 Consider the following two expressions, which have the same value. Which one will typically be more relevant in NLP Why 9788 We have seen how to represent a sentence as a list of words, where each word is a sequence of characters. What does sent122 do Why Experiment with other index values. 9788 The first sentence of text3 is provided to you in the variable sent3 . The index of the in sent3 is 1, because sent31 gives us the . What are the indexes of the two other occurrences of this word in sent3 9788 Review the discussion of conditionals in 1.4. Find all words in the Chat Corpus ( text5 ) starting with the letter b. Show them in alphabetical order. 9788 Type the expression range(10) at the interpreter prompt. Now try range(10, 20) . range(10, 20, 2) . and range(20, 10, -2) . We will see a variety of uses for this built-in function in later chapters. 9681 Use text9.index() to find the index of the word sunset. Youll need to insert this word as an argument between the parentheses. By a process of trial and error, find the slice for the complete sentence that contains this word. 9681 Using list addition, and the set and sorted operations, compute the vocabulary of the sentences sent1 . sent8 . 9681 What is the difference between the following two lines Which one will give a larger value Will this be the case for other texts

No comments:

Post a Comment