Skip to content

Instantly share code, notes, and snippets.

@mjlassila
Created October 29, 2012 12:03
Show Gist options
  • Save mjlassila/3973189 to your computer and use it in GitHub Desktop.
Save mjlassila/3973189 to your computer and use it in GitHub Desktop.
ITIA41 - Viikkoharjoitusten esimerkkiratkaisuja 6
#### Tehtävä 1 ####
# Tätä tehtävää ratkaistaessa saattoi aiheuttaa ihmetystä, jollei tiedostoa
# sulkenut kirjoittamisen jälkeen. Tällöin varsinainen kirjoitusoperaatio jää
# tapahtumatta ja tapahtuu vasta silloin, kun Python sulkee automaattisesti
# tiedoston. Auki jäänyt tiedosto näyttäytyi cat-komennolla tarkasteltuna
# tyhjältä, vaikka tiedostoon olisikin kirjoitettu write:llä.
# Eräs ratkaisu
from nltk.tokenize import *
text = open('/home/courses/itima41/wikileaks-estonia.txt').read()
stemmed_wikileaks = open('stemmed-wikileaks.txt', 'w')
suffixes = ['ing', 'ly', 'ed', 'ious', 'ies', 'ive', 'es', 'ment', 'er']
tokenized_text = word_tokenize(text)
for token in tokenized_text:
for suffix in suffixes:
if token.endswith(suffix):
stem = token[:-len(suffix)]
stemmed_wikileaks.write(stem + '\n')
# Suljetaan lopuksi tiedosto
stemmed_wikileaks.close()
#### Tehtävä 2 ####
# Joissain ratkaisuissa oli huomioitu myös pyörän osien (l. meronyymien) meronyymit.
# Hienostu huomattu, sillä tätä ei erikseen vaadittu! Tarkkuutta vaadittiin siinä,
# että listauksiin otti mukaan vain bicycle-sanan substantiivimuodon synsetit.
# Bicycle löytyy Wordnetistä myös verbinä.
# Eräs ratkaisu:
import nltk
from nltk.corpus import wordnet as wn
# Tutkitaan bicycle-sanan substantiivimuotoja
>>> bicycles = wn.synsets('bicycle', wn.NOUN)
>>> len(bicycles)
1
# Bicycle-substantiivilla on siis vain yksi synsetti
# Ladataan synsetti
bicycle = bicycles[0]
# hyponyymit
>>> bicycle_hyponyms = bicycle.hyponyms()
>>> for bicycle_hyponym in bicycle_hyponyms:
... bicycle_hyponym.lemma_names
...
['velocipede']
['push-bike']
['bicycle-built-for-two', 'tandem_bicycle', 'tandem']
['safety_bicycle', 'safety_bike']
['ordinary', 'ordinary_bicycle']
['mountain_bike', 'all-terrain_bike', 'off-roader']
# meronyymmit
>>> bicycle_meronyms = bicycle.part_meronyms()
>>> for bicycle_meronym in bicycle_meronyms:
... print bicycle_meronym.lemma_names
...
['kickstand']
['chain']
['bicycle_wheel']
['pedal', 'treadle', 'foot_pedal', 'foot_lever']
['bicycle_seat', 'saddle']
['mudguard', 'splash_guard', 'splash-guard']
['handlebar']
['coaster_brake']
['sprocket', 'sprocket_wheel']
# välittömät hyperonyymit
>>> bicycle_hypernyms = bicycle.hypernyms()
>>> for bicycle_hypernym in bicycle_hypernyms:
... bicycle_hypernym.lemma_names
...
['wheeled_vehicle']
#### Tehtävä 3 ####
# Määritelmiä ja käyttöesimerkkejä tulostettaessa täytyi huomata varautua siihen,
# etteivät kaikki set-sanan substantiivimuodon merkitykset sisältäneet niitä.
# Eräs ratkaisu:
file = open('definitions.txt', 'w')
from nltk.corpus import wordnet as wn
set_of_noun_sets = wn.synsets('set', wn.NOUN )
for set in set_of_noun_sets:
lemma_names = wn.synset(set.name).lemma_names
definition = wn.synset(set.name).definition
examples = wn.synset(set.name).examples
# Yhdistetään muodot pilkulla.
joined_lemma_names = ', '.join(lemma_names)
# Muutetaan määritelmä alkamaan isolla kirjaimella
titlecase_definition = definition.capitalize()
# Aloitetaan määritelmärivin koostaminen luomalla tyhjä merkkijono
line_in_dictionary = ''
# Liitetään määritelmäriviin sanamuodot
line_in_dictionary += joined_lemma_names + '. '
# Jos synsetti sisältää määritelmän, otetaan se mukaan
if definition:
line_in_dictionary += titlecase_definition +'. '
# Otetaan mukaan mahdolliset käyttöesimerkit
if examples:
line_in_dictionary +='Usage examples: ' + '; '.join(examples) + '.'
file.write(line_in_dictionary + '\n')
file.close()
#### Tehtävä 4 ####
# Tämä tehtävä demonstroi, kuinka suhteellisen hyvästä tarkkuudestaan huolimatta
# (jopa yli 95%), automaattinen lauseenjäsennys ei ole erehtymätön työkalu.
# Tehtävässä käytetty Penn Treebank Tagger tunnisti väärin esimerkkilauseen
# kolme sanaa:
#
# - Great -- interjektio, tulkittiin erisnimeksi
# - park -- substantiivi, tulkittiin vebiksi
# - stroll -- verbi, tulkittiin substantiiviksi
#
# Tavanomaisella tekstiaineistolla lauseenjäsentimen tuottamat tulokset ovat
# selvästi parempia, sillä # esimerkkilause oli muotoiltu tuomaan esille juuri
# tämänkaltaisia ongelmia.
# Eräs ratkaisu
>>> import nltk
>>> from nltk.tokenize import *
>>> from nltk.tag import *
>>> text = "Great, she and old Edward stroll to park slowly."
>>> tokens = word_tokenize(text)
# Tehdään lauseenjäsennys
>>> tokens_with_pos = pos_tag(tokens)
>>> for token_with_pos in tokens_with_pos:
... nltk.help.upenn_tagset(token_with_pos[1])
#### Tehtävä 5 ####
# Tehtävää ratkaistaessa täytyi olla tarkkana, että vertailun tuli tehneeksi pelejä
# eikä sanojen muita merkityksiä edustavien synsettien kesken. Tehtävänannon yhteydessä
# olevassa tulostusmuotoesimerkissä vertailu oli tehty mielivaltaisten synsettien välillä
# tarkastamatta, oliko kyseinen synsetti peleihin liittyvä.
# Katsotaan aluksi, että verrataan oikeita synsettejä
games = ['poker', 'chess', 'football', 'lottery']
for game in games:
for synset in wn.synsets(game):
print synset.name + ' ' + synset.definition
# Valitaan oikeat synsetit tulostettujen määritelmien perusteella
poker.n.01 fire iron consisting of a metal rod with a handle; used to stir a fire
poker.n.02 any of various card games in which players bet that they hold the highest-ranking hand
chess.n.01 weedy annual native to Europe but widely distributed as a weed especially in wheat
chess.n.02 a board game for two players who move their 16 pieces according to specific rules; the object is to checkmate the opponent's king
football.n.01 any of various games played with a ball (round or oval) in which two teams try to kick or carry or propel the ball into each other's goal
football.n.02 the inflated oblong ball used in playing American football
lottery.n.01 something that is regarded as a chance event
lottery.n.02 players buy (or are given) chances and prizes are distributed by casting lots
# itertools-kirjaston combinations-metodi luo sille annetusta listasta halutun mittaisia yhdistelmiä.
for gamepair in itertools.combinations(['poker.n.02', 'chess.n.02', 'football.n.01', 'lottery.n.02'], 2):
# Erotetaan synsetin nimestä pelin nimi
first_game_name = gamepair[0].split('.')[0]
second_game_name = gamepair[1].split('.')[0]
# Parannetaan lukukelpoisuutta nimeällä muuttujat selkokielisesti
compare_to = gamepair[0]
comparison = gamepair[1]
compare_to_synset = wordnet.synset(compare_to)
comparison_synset = wordnet.synset(comparison)
metric = compare_to_synset.wup_similarity(comparison_synset)
print first_game_name +' ~ ' + second_game_name + ' ' + str(metric)
# Tuloksena saatiin
poker ~ chess 0.736842105263
poker ~ football 0.7
poker ~ lottery 0.777777777778
chess ~ football 0.666666666667
chess ~ lottery 0.736842105263
football ~ lottery 0.7
# Wu-Palmer -samalkaltaisuus -metodia (wup_similiarity) kokeillessaan saattoi
# huomata, että verratessa lottery-synsettiä itseensä, saadaan hieman oudolta
# tuntuva 0,75 arvon. Olisihan loogista, jos arvo olisi 1.
# Selitys tälle voi olla tässä (lähde: http://nltk.googlecode.com/svn/trunk/doc/howto/wordnet.html)
# "Wu-Palmer Similarity: Return a score denoting how similar two word senses are,
# based on the depth of the two senses in the taxonomy and that of their
# Least Common Subsumer (most specific ancestor node).
# The LCS does not necessarily feature in the shortest path connecting
# the two senses, as it is by definition the common ancestor deepest in
# the taxonomy, not closest to the two senses. Typically, however, it will so
# feature. Where multiple candidates for the LCS exist, that whose shortest
# path to the root node is the longest will be selected. Where the LCS has multiple
# paths to the root, the longer path is used for the purposes of the calculation."
# Lottery-synsetin välittömään esi-isään (game_of_chance) kulkee kolme polkua,
# jotka kaikki liittyvät ylemmällä hierarkiassa activity-synsettiin
# (http://bitly.com/wordnet-lottery). Nähtävästi laskennassa ei käytetä aina
# määritelmän mukaisesti pisintä polkua.
# Jos keksitte tälle ilmiölle paremman selityksen, kertokaa siitä toki pulmapalstalla :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment