예제 #1
0
   def do_exit(self, i, j, total, next, last_i, last_j):
      """Process the end of a floor"""

      self.FOUND_EXIT = True

      # Place the last path on the image
      if next[2] in ['e', 'w']:
         self.IMAGE.filledRectangle((last_i * 15 + 7, last_j * 15 + 6), (i * 15 + 7, j * 15 + 8), self.COLORS['green'])
      else:
         self.IMAGE.filledRectangle((last_i * 15 + 6, last_j * 15 + 7), (i * 15 + 8, j * 15 + 7), self.COLORS['green'])

      # Increment chapter, and write it
      self.CHAPTER += 1
      self.TEXT += "~~~ CHAPTER " + numerals(str(self.CHAPTER)).upper() + " ~~~\n"
      self.TEXT += self.TEMP
      self.TEXT += "Then I " + random.choice(self.WALK) + " down a flight of stairs. "

      # Write the current map out to PNG
      self.IMAGE.writePng("html/maps/" + str(self.CHAPTER) + ".png")

      # Check to see if any animals stopped following the narrator, then print them
      self.TEXT += self.unfollow()
      self.get_animals_following()
      self.get_flowers_held()

      # Print the percent of this floor explored
      self.TEXT += "It seemed like I had explored about " 
      self.TEXT += numerals(str(self.count_visited() * 1.0 / (self.MAZE_SIZE * self.MAZE_SIZE) * 100).split('.')[0])
      self.TEXT += " percent of this floor.\n"

      # Logging...
      logging.info('--- CHAPTER ' + str(self.CHAPTER) + ' ---')
      logging.info('Found the exit to the maze at (' + str(i) + ',' + str(j) + ')')
      logging.info('Total steps: ' + str(total))
예제 #2
0
 def x_oclock_in_the():
     if not h in [0,12]:
         if h < 12:
             time_str_list.append(numerals(h))
         else:
             time_str_list.append(numerals(h-12))
         time_str_list.append("o'clock")
         if h < 12:
             time_str_list.append('in the morning')
         elif h > 17:
             time_str_list.append('in the evening')
         else:
             time_str_list.append('in the afternoon')
예제 #3
0
 def test_number(self):
     # Assert numeric string = actual number (after rounding).
     for i in range(100):
         x = random.random()
         y = en.number(en.numerals(x, round=10))
         self.assertAlmostEqual(x, y, places=10)
     print("pattern.en.number()")
예제 #4
0
 def test_number(self):
     # Assert numeric string = actual number (after rounding).
     for i in range(100):
         x = random.random()
         y = en.number(en.numerals(x, round=10))
         self.assertAlmostEqual(x, y, places=10)
     print "pattern.en.number()"
예제 #5
0
    def do_exit(self, i, j, total, next, last_i, last_j):
        """Process the end of a floor"""

        self.FOUND_EXIT = True

        # Place the last path on the image
        if next[2] in ['e', 'w']:
            self.IMAGE.filledRectangle((last_i * 15 + 7, last_j * 15 + 6),
                                       (i * 15 + 7, j * 15 + 8),
                                       self.COLORS['green'])
        else:
            self.IMAGE.filledRectangle((last_i * 15 + 6, last_j * 15 + 7),
                                       (i * 15 + 8, j * 15 + 7),
                                       self.COLORS['green'])

        # Increment chapter, and write it
        self.CHAPTER += 1
        self.TEXT += "~~~ CHAPTER " + numerals(str(
            self.CHAPTER)).upper() + " ~~~\n"
        self.TEXT += self.TEMP
        self.TEXT += "Then I " + random.choice(
            self.WALK) + " down a flight of stairs. "

        # Write the current map out to PNG
        self.IMAGE.writePng("html/maps/" + str(self.CHAPTER) + ".png")

        # Check to see if any animals stopped following the narrator, then print them
        self.TEXT += self.unfollow()
        self.get_animals_following()
        self.get_flowers_held()

        # Print the percent of this floor explored
        self.TEXT += "It seemed like I had explored about "
        self.TEXT += numerals(
            str(self.count_visited() * 1.0 /
                (self.MAZE_SIZE * self.MAZE_SIZE) * 100).split('.')[0])
        self.TEXT += " percent of this floor.\n"

        # Logging...
        logging.info('--- CHAPTER ' + str(self.CHAPTER) + ' ---')
        logging.info('Found the exit to the maze at (' + str(i) + ',' +
                     str(j) + ')')
        logging.info('Total steps: ' + str(total))
예제 #6
0
 def test_numerals(self):
     # Assert number to numerals.
     for x, s in (
         (1.5, "one point five"), (15, "fifteen"),
         (150, "one hundred and fifty"), (151, "one hundred and fifty-one"),
         (1510, "one thousand five hundred and ten"),
         (15101, "fifteen thousand one hundred and one"),
         (150101, "one hundred and fifty thousand one hundred and one"),
         (1500101,
          "one million, five hundred thousand one hundred and one")):
         self.assertEqual(en.numerals(x), s)
     print "pattern.en.numerals()"
예제 #7
0
 def test_numerals(self):
     # Assert number to numerals.
     for x, s in (
       (    1.5, "one point five"),
       (     15, "fifteen"),
       (    150, "one hundred and fifty"),
       (    151, "one hundred and fifty-one"),
       (   1510, "one thousand five hundred and ten"),
       (  15101, "fifteen thousand one hundred and one"),
       ( 150101, "one hundred and fifty thousand one hundred and one"),
       (1500101, "one million, five hundred thousand one hundred and one")):
         self.assertEqual(en.numerals(x), s)
     print "pattern.en.numerals()"
예제 #8
0
   def get_flowers_held(self):
      """Get a textual representation of flowers currently held by the narrator"""

      if self.FLOWERS:
         if not self.ANIMALS:
            self.TEXT += "So far "

         self.TEXT += "I held " + numerals(len(self.FLOWERS)) + " flower"

         if len(self.FLOWERS) > 1:
            self.TEXT += "s"

         self.TEXT += ". "
예제 #9
0
    def normal_time():
        if h == 0:
            time_str_list.append('twelve')
        elif 0 < h < 13:
            time_str_list.append(numerals(h))
        else:
            time_str_list.append(numerals(h-12))

        time_str_list.append(numerals(m))

        if h in [0,12]:
            if h == 0:
                time_str_list.append('ante meridiem')
            else:
                time_str_list.append('post meridiem')
        else:
            if 0 < h < 12:
                time_str_list.append('in the morning')
            elif h > 17:
                time_str_list.append('in the evening')
            else:
                time_str_list.append('in the afternoon')        
예제 #10
0
    def get_flowers_held(self):
        """Get a textual representation of flowers currently held by the narrator"""

        if self.FLOWERS:
            if not self.ANIMALS:
                self.TEXT += "So far "

            self.TEXT += "I held " + numerals(len(self.FLOWERS)) + " flower"

            if len(self.FLOWERS) > 1:
                self.TEXT += "s"

            self.TEXT += ". "
예제 #11
0
   def get_animals_following(self):
      """Retrieve a textual list of animals currently following the narrator"""

      if self.ANIMALS:
         self.TEXT += "So far " + numerals(len(self.ANIMALS)) + " animal"

         if len(self.ANIMALS) > 1:
            self.TEXT += "s were following me"
         else:
            self.TEXT += " was following me"

         if self.FLOWERS:
            self.TEXT += ", and "

         else:
            self.TEXT += ". "
예제 #12
0
    def get_animals_following(self):
        """Retrieve a textual list of animals currently following the narrator"""

        if self.ANIMALS:
            self.TEXT += "So far " + numerals(len(self.ANIMALS)) + " animal"

            if len(self.ANIMALS) > 1:
                self.TEXT += "s were following me"
            else:
                self.TEXT += " was following me"

            if self.FLOWERS:
                self.TEXT += ", and "

            else:
                self.TEXT += ". "
예제 #13
0
def time_parse():
    dt = datetime.now()

    h = dt.hour
    m = dt.minute

    time_str_list = list()

    time_str_list.append(rc(['The time was', 'It was']))
    
    def midnight_noon():
        if h == 0:
            time_str_list.append('midnight')
        elif h == 12:
            time_str_list.append('noon')

    def x_oclock_in_the():
        if not h in [0,12]:
            if h < 12:
                time_str_list.append(numerals(h))
            else:
                time_str_list.append(numerals(h-12))
            time_str_list.append("o'clock")
            if h < 12:
                time_str_list.append('in the morning')
            elif h > 17:
                time_str_list.append('in the evening')
            else:
                time_str_list.append('in the afternoon')

    def normal_time():
        if h == 0:
            time_str_list.append('twelve')
        elif 0 < h < 13:
            time_str_list.append(numerals(h))
        else:
            time_str_list.append(numerals(h-12))

        time_str_list.append(numerals(m))

        if h in [0,12]:
            if h == 0:
                time_str_list.append('ante meridiem')
            else:
                time_str_list.append('post meridiem')
        else:
            if 0 < h < 12:
                time_str_list.append('in the morning')
            elif h > 17:
                time_str_list.append('in the evening')
            else:
                time_str_list.append('in the afternoon')        


    if m == 0:
        if h in [0,12]:
            midnight_noon()
        x_oclock_in_the()

    elif 0 < m < 15:
        time_str_list.append(numerals(m))

        if m == 1:
            time_str_list.append('minute')
        else:
            time_str_list.append('minutes')

        time_str_list.append(rc(['past', 'after']))

        if h in [0,12]:
            midnight_noon()
        else:
            x_oclock_in_the()

    elif m == 15:
        time_str_list.append('quarter')
        time_str_list.append(rc(['past', 'after']))
        if h in [0,12]:
            midnight_noon()
        else:
            x_oclock_in_the()

    elif 15 < m < 30:
        normal_time()

    elif m == 30:
        time_str_list.append('half past')
        if h in [0,12]:
            midnight_noon()
        else:
            x_oclock_in_the()

    elif 30 < m < 45:
        normal_time()

    elif m == 45:
        time_str_list.append('quarter')
        time_str_list.append(rc(['to', 'until']))
        if h == 11:
            time_str_list.append('noon')
        elif h == 23:
            time_str_list.append('midnight')
        else:
            h += 1
            x_oclock_in_the()

    elif 45 < m < 50:
        normal_time()

    elif 50 <= m <= 59:
        time_str_list.append(numerals(60-m))

        if m == 59:
            time_str_list.append('minute')
        else:
            time_str_list.append('minutes')

        time_str_list.append(rc(['to', 'until']))

        if h == 11:
            time_str_list.append('noon')
        elif h == 23:
            time_str_list.append('midnight')
        else:
            h += 1
            x_oclock_in_the()

    return ' '.join(time_str_list)
예제 #14
0
# ### Spelling Corrections

from pattern.en import suggest

print(suggest("Whitle"))

from pattern.en import suggest
print(suggest("Fracture"))

# ### Working with Numbers

from pattern.en import number, numerals

print(number("one hundred and twenty two"))
print(numerals(256.390, round=2))

from pattern.en import quantify

print(
    quantify([
        'apple', 'apple', 'apple', 'banana', 'banana', 'banana', 'mango',
        'mango'
    ]))

from pattern.en import quantify

print(quantify({'strawberry': 200, 'peach': 15}))
print(quantify('orange', amount=1200))

# ## Pattern Library Functions for Data Mining
예제 #15
0
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from pattern.en import number, numerals, quantify, reflect

# The number() command returns an int or float from a written representation.
# This is useful, for example, in combination with a parser
# to transform "CD" parts-of-speech to actual numbers.
# The algorithm ignores words that aren't recognized as numerals.
print(number("two thousand five hundred and eight"))
print(number("two point eighty-five"))
print("")

# The numerals() command returns a written representation from an int or float.
print(numerals(1.249, round=2))
print(numerals(1.249, round=3))
print("")

# The quantify() commands uses pluralization + approximation to enumerate words.
# This is useful to generate a human-readable summary of a set of strings.
print(quantify(["goose", "goose", "duck", "chicken", "chicken", "chicken"]))
print(quantify(["penguin", "polar bear"]))
print(quantify(["carrot"] * 1000))
print(quantify("parrot", amount=1000))
print(quantify({"carrot": 100, "parrot": 20}))
print("")

# The quantify() command only works with words (strings).
# To quantify a set of Python objects, use reflect().
# This will first create a human-readable name for each object and then quantify these.
예제 #16
0
import os, sys; sys.path.insert(0, os.path.join("..", ".."))

from pattern.en import number, numerals, quantify, reflect

# The number() command returns an int or float from a written representation.
# This is useful, for example, in combination with a parser 
# to transform "CD" parts-of-speech to actual numbers.
# The algorithm ignores words that aren't recognized as numerals.
print number("two thousand five hundred and eight")
print number("two point eighty-five")
print

# The numerals() command returns a written representation from an int or float.
print numerals(1.249, round=2)
print numerals(1.249, round=3)
print

# The quantify() commands uses pluralization + approximation to enumerate words.
# This is useful to generate a human-readable summary of a set of strings.
print quantify(["goose", "goose", "duck", "chicken", "chicken", "chicken"])
print quantify(["penguin", "polar bear"])
print quantify(["carrot"] * 1000)
print quantify("parrot", amount=1000)
print quantify({"carrot": 100, "parrot": 20})
print

# The quantify() command only works with words (strings).
# To quantify a set of Python objects, use reflect().
# This will first create a human-readable name for each object and then quantify these.
print reflect([0, 1, {}, False, reflect])
print reflect(os.path)
예제 #17
0
import os, sys

sys.path.insert(0, os.path.join("..", "..", ".."))

from pattern.en import number, numerals, quantify, reflect

# The number() command returns an int or float from a written representation.
# This is useful, for example, in combination with a parser
# to transform "CD" parts-of-speech to actual numbers.
# The algorithm ignores words that aren't recognized as numerals.
print number("two thousand five hundred and eight")
print number("two point eighty-five")
print

# The numerals() command returns a written representation from an int or float.
print numerals(1.249, round=2)
print numerals(1.249, round=3)
print

# The quantify() commands uses pluralization + approximation to enumerate words.
# This is useful to generate a human-readable summary of a set of strings.
print quantify(["goose", "goose", "duck", "chicken", "chicken", "chicken"])
print quantify(["penguin", "polar bear"])
print quantify(["carrot"] * 1000)
print quantify("parrot", amount=1000)
print quantify({"carrot": 100, "parrot": 20})
print

# The quantify() command only works with words (strings).
# To quantify a set of Python objects, use reflect().
# This will first create a human-readable name for each object and then quantify these.
예제 #18
0
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from pattern.en import number, numerals, quantify, reflect

# The number() command returns an int or float from a written representation.
# This is useful, for example, in combination with a parser
# to transform "CD" parts-of-speech to actual numbers.
# The algorithm ignores words that aren't recognized as numerals.
print(number("two thousand five hundred and eight"))
print(number("two point eighty-five"))
print()

# The numerals() command returns a written representation from an int or float.
print(numerals(1.249, round=2))
print(numerals(1.249, round=3))
print()

# The quantify() commands uses pluralization + approximation to enumerate words.
# This is useful to generate a human-readable summary of a set of strings.
print(quantify(["goose", "goose", "duck", "chicken", "chicken", "chicken"]))
print(quantify(["penguin", "polar bear"]))
print(quantify(["carrot"] * 1000))
print(quantify("parrot", amount=1000))
print(quantify({"carrot": 100, "parrot": 20}))
print()

# The quantify() command only works with words (strings).
# To quantify a set of Python objects, use reflect().
# This will first create a human-readable name for each object and then
예제 #19
0
print superlative('bad')
# verb conjugation
print lexeme('purr')
print lemma('purring')
print conjugate('purred', '3sg')  # he / she / it
print 'p' in tenses('purred')  # By alias.
print PAST in tenses('purred')
print(PAST, 1, PL) in tenses('purred')
# rule-based conjugation
print 'google' in verbs.infinitives
print 'googled' in verbs.inflections
print conjugate('googled', tense=PARTICIPLE, parse=False)
print conjugate('googled', tense=PARTICIPLE, parse=True)
# quantification
print number("seventy-five point two")  # "seventy-five point two" => 75.2
print numerals(2.245, round=2)  # 2.245 => "two point twenty-five"
print quantify(['goose', 'goose', 'duck', 'chicken', 'chicken', 'chicken'])
print quantify({'carrot': 100, 'parrot': 20})
print quantify('carrot', amount=1000)
# spelling
print suggest("parot")
# n-grams
print ngrams("I am eating pizza.", n=2)  # bigrams
print ngrams("I am eating pizza.",
             n=3,
             punctuation=".,;:!?()[]{}`''\"@#$^&*+-|=~_",
             continuous=False)
# parser
print parse(
    'I eat pizza with a fork.',
    tokenize=True,  # Split punctuation marks from words?