Пример #1
0
    def test_split(self):
        """Test method :meth:`plugins.enhancedstring.EnhancedString.split`

        **Tested:**

        - The returned list of enhanced strings is correct when using a single delimiter.
        - The returned list of enhanced strings is correct when using multiple delimiters.
        """
        text = (
            "This text ends sentences with dots. Does it also end sentences with question "
            "marks? Yes it does! Oh look, it even has exclamation marks!")

        result = enhancedstring.EnhancedString(text).split()
        expected = list(map(enhancedstring.EnhancedString, text.split()))
        self.assertEqual(result, expected)

        result = enhancedstring.EnhancedString(text).split('.')
        expected = list(map(enhancedstring.EnhancedString, text.split('.')))
        self.assertEqual(result, expected)

        result = enhancedstring.EnhancedString(text).split(['.', '!', '?'])
        expected = list(
            map(enhancedstring.EnhancedString, [
                "This text ends sentences with dots",
                " Does it also end sentences with question marks",
                " Yes it does",
                " Oh look, it even has exclamation marks",
                "",
            ]))
        self.assertEqual(result, expected)
Пример #2
0
    def test_strip(self):
        """Test method :meth:`plugins.enhancedstring.EnhancedString.strip`

        **Tested:**

        - The returned stripped enhanced string is correct.
        """
        text = "   Allow me to tease you with a strip.   "
        result = enhancedstring.EnhancedString(text).strip()
        expected = enhancedstring.EnhancedString(
            "Allow me to tease you with a strip.")
        self.assertEqual(result, expected)
Пример #3
0
    def test___eq__(self):
        """Test method :meth:`plugins.enhancedstring.EnhancedString.__str__`

        **Tested:**

        - False is returned when it should.
        - True is returned when it should.
        """
        s0 = enhancedstring.EnhancedString("This is an enhanced string.")
        s1 = "This is a regular string."
        s2 = enhancedstring.EnhancedString("This is another enhanced string.")
        s3 = enhancedstring.EnhancedString("This is an enhanced string.")
        self.assertFalse(s0 == s1)
        self.assertFalse(s0 == s2)
        self.assertTrue(s0 == s3)
Пример #4
0
    def test_lines(self):
        """Test property :meth:`plugins.enhancedstring.EnhancedString.lines`

        **Tested:**

        - The enhanced string is correctly split in a list of enhanced strings for each line.
        """
        s1 = enhancedstring.EnhancedString(
            "This string has\nmultiple lines!\n")
        result = s1.lines
        expected = [
            enhancedstring.EnhancedString("This string has"),
            enhancedstring.EnhancedString("multiple lines!"),
            enhancedstring.EnhancedString(""),
        ]
        self.assertEqual(result, expected)
Пример #5
0
    def test_is_palindrome(self):
        """Test method :meth:`plugins.enhancedstring.EnhancedString.is_palindrome`

        **Tested:**

        - Returns True for a simple palindrome consisting only of alphanumeric characters.
        - Returns True for a palindrome containing non-alphanumeric characters.
        - Returns False for a non-palindrome.
        """
        self.assertTrue(
            enhancedstring.EnhancedString('racecar').is_palindrome())
        self.assertFalse(
            enhancedstring.EnhancedString('racetruck').is_palindrome())
        self.assertTrue(
            enhancedstring.EnhancedString("Dammit, I'm mad!").is_palindrome())
        self.assertFalse(
            enhancedstring.EnhancedString("Damn it, I'm mad!").is_palindrome())
Пример #6
0
def run():
    """Execute the challenges.037e module."""
    fil_fn = utils.get_input("Provide input file name > ")
    fil_fp = os.path.join(cfg.input_dir, fil_fn)
    with open(fil_fp, 'r') as fil:
        text = es.EnhancedString(fil.read())
    print("Amount of lines in file: {}".format(text.nlines))
    print("Amount of words in file: {}".format(text.nwords))
Пример #7
0
    def test___init__(self):
        """Test method :meth:`plugins.enhancedstring.EnhancedString.__init__`

        **Tested:**

        - The attributes of an enhanced string are correct after initialization.
        """
        str_ = enhancedstring.EnhancedString('test123')
        self.assertEqual(str_.str_, 'test123')
Пример #8
0
    def test___len__(self):
        """Test method :meth:`plugins.enhancedstring.EnhancedString.__len__`

        **Tested:**

        - The returned string length is correct.
        """
        str_ = enhancedstring.EnhancedString('test123')
        self.assertEqual(str_.__len__(), 7)
Пример #9
0
    def test_remove(self):
        """Test method :meth:`plugins.enhancedstring.EnhancedString.remove`

        **Tested:**

        - The passed characters are correctly removed from the enhanced string.
        """
        str_ = enhancedstring.EnhancedString('abcdaabbccddaaabbbcccddd')
        str_.remove('bc')
        self.assertEqual(str(str_), 'adaaddaaaddd')
Пример #10
0
def run():
    """Execute the challenges.019e module."""
    # Load the text file from the URL and split in lines.
    print("Start downloading and processing the book. This may take a while...")
    start = 57
    end = 12681
    target_url = 'http://www.gutenberg.org/cache/epub/1661/pg1661.txt'
    book = urlopen(target_url).read().decode('utf-8')
    lines = book.split('\r\n')

    # Go over all lines, excluding the Gutenberg header and footer, book title
    # and chapter index.
    counts = {}
    nlines_empty = 0
    lines_skipped = []
    nlines_counted = 0
    for line in lines[start:end]:
        if line == '':  ## Skip empty lines.
            nlines_empty += 1
        elif line == line.upper() and line[0] in 'IVXA':  ## Allcaps lines that start with one of 'IVXA' are considered story or chapter titles.
            lines_skipped.append(line)
        else:  ## If none of the previous, then the line should be counted.
            nlines_counted += 1
            counts = estr.EnhancedString(line).count_characters(counts=counts)

    # Crunch the numbers.
    ## Line count
    nlines_skipped = len(lines_skipped)
    nlines_total = nlines_empty + nlines_skipped + nlines_counted
    nlines_expected = end - start

    ## Character counts
    nchars_an = sum([counts[char] for char in counts if char.isalnum()])
    nchars_nospace = sum([counts[char] for char in counts if char != ' '])
    nchars_all = sum([counts[char] for char in counts])

    # Print a report.
    print('\n' + format_header("LINES", above='=', below='='))
    print('\n' + format_header("Line count", below="'"))
    print("Analysis started on line {} and stopped on line {}".format(start, end))
    print("Amount of empty lines: {}".format(nlines_empty))
    print("Amount of skipped, non-empty lines: {}".format(nlines_skipped))
    print("Amount of counted lines: {}".format(nlines_counted))
    print("Total amount of lines: {}".format(nlines_total))
    print("Expected amount of lines: {}".format(nlines_expected))
    print('\n' + format_header("Skipped, non-empty lines", below="'"))
    print('\n'.join(lines_skipped))
    print('\n' + format_header("CHARACTER COUNTS", above='=', below='='))
    print('\n' + format_header("Individual characters", below="'"))
    print('\n'.join(['{}: {}'.format(char, nr) for char, nr in counts.items()]))
    print('\n' + format_header("Groups of characters", below="'"))
    print("Amount of alphanumeric characters: {}".format(nchars_an))
    print("Total amount of characters (without spaces): {}".format(nchars_nospace))
    print("Total amount of characters (including spaces): {}".format(nchars_all))
Пример #11
0
    def test_nwords(self):
        """Test property :meth:`plugins.enhancedstring.EnhancedString.nwords`

        **Tested:**

        - The returned amount of words is correct.
        """
        s1 = enhancedstring.EnhancedString("This string has multiple words!")
        result = s1.nwords
        expected = 5
        self.assertEqual(result, expected)
Пример #12
0
    def test_nlines(self):
        """Test property :meth:`plugins.enhancedstring.EnhancedString.nlines`

        **Tested:**

        - The returned amount of lines is correct.
        """
        s1 = enhancedstring.EnhancedString(
            "This string has\nmultiple lines!\n")
        result = s1.nlines
        expected = 3
        self.assertEqual(result, expected)
Пример #13
0
def run():
    """Execute the challenges.029e module."""
    str_ = es.EnhancedString(utils.get_input("Give me a string: "))
    options = {True: "It's a palindrome!", False: "Nope, not a palindrome."}
    print(options[str_.is_palindrome()])

    poem = es.EnhancedString("""Dammit I'm mad.
Evil is a deed as I live.
God, am I reviled? I rise, my bed on a sun, I melt.
To be not one man emanating is sad. I piss.
Alas, it is so late. Who stops to help?
Man, it is hot. I'm in it. I tell.
I am not a devil. I level "Mad Dog".
Ah, say burning is, as a deified gulp,
In my halo of a mired rum tin.
I erase many men. Oh, to be man, a sin.
Is evil in a clam? In a trap?
No. It is open. On it I was stuck.
Rats peed on hope. Elsewhere dips a web.
Be still if I fill its ebb.
Ew, a spider... eh?
We sleep. Oh no!
Deep, stark cuts saw it in one position.
Part animal, can I live? Sin is a name.
Both, one... my names are in it.
Murder? I'm a fool.
A hymn I plug, deified as a sign in ruby ash,
A Goddam level I lived at.
On mail let it in. I'm it.
Oh, sit in ample hot spots. Oh wet!
A loss it is alas (sip). I'd assign it a name.
Name not one bottle minus an ode by me:
"Sir, I deliver. I'm a dog"
Evil is a deed as I live.
Dammit I'm mad.""")
    print(
        "Extra: Is the poem 'Dammit I'm Mad' from Demetri Martin a palindrome?"
    )
    options = {True: "Yes it is!", False: "No it's not... (huh?)"}
    print(options[poem.is_palindrome()])
Пример #14
0
    def test_count_characters(self):
        """Test method :meth:`plugins.enhancedstring.EnhancedString.count_characters`

        **Tested:**

        - The character count has been correctly added to a new dictionary.
        - The character count has been correctly added to an existing dictionary.
        - The dictionary to which a count is added is not changed in-place.
        """
        s1 = enhancedstring.EnhancedString('aaa bb c . !')
        s2 = enhancedstring.EnhancedString('a dd eeee')
        count1 = s1.count_characters()
        self.assertEqual(count1, {
            'a': 3,
            'b': 2,
            'c': 1,
            ' ': 4,
            '.': 1,
            '!': 1
        })
        count2 = s2.count_characters(counts=count1)
        self.assertEqual(count2, {
            'a': 4,
            'b': 2,
            'c': 1,
            'd': 2,
            'e': 4,
            ' ': 6,
            '.': 1,
            '!': 1
        })
        self.assertEqual(count1, {
            'a': 3,
            'b': 2,
            'c': 1,
            ' ': 4,
            '.': 1,
            '!': 1
        })
Пример #15
0
    def test_frame_with_ascii(self):
        """Test method :meth:`plugins.enhancedstring.EnhancedString.frame_with_ascii`

        **Tested:**

        - The returned enhanced string is correct.
        """
        text = "Hello World!\nSo long and thanks for all the fish...\nYay, I'm a programmer now!"
        result = enhancedstring.EnhancedString(text).frame_with_ascii(char='@',
                                                                      mfl=30,
                                                                      a='^')
        expected = enhancedstring.EnhancedString('\n'.join([
            "@@@@@@@@@@@@@@@@@@@@@@@@@@@@",
            "@                          @",
            "@       Hello World!       @",
            "@  So long and thanks for  @",
            "@     all the fish...      @",
            "@  Yay, I'm a programmer   @",
            "@           now!           @",
            "@                          @",
            "@@@@@@@@@@@@@@@@@@@@@@@@@@@@",
        ]))
        self.assertEqual(result, expected)
Пример #16
0
def run():
    """Execute the challenges.015e module."""
    # Get user input.
    textinfn = utils.get_input("Input file? > ")
    a = utils.get_input("Desired alignment ('<', '>', '^')? > ")
    textoutfn = utils.get_input("Output file? > ")

    # Read, align and write.
    textinfp = os.path.join(cfg.input_dir, textinfn)
    textoutfp = os.path.join(cfg.output_dir, textoutfn)
    with open(textinfp, 'r') as textinfil:
        text = estr.EnhancedString(textinfil.read())
    text.align(a)
    with open(textoutfp, 'w') as textoutfil:
        textoutfil.write(str(text))
    print("Note: Data has been written to file '{}'.".format(textoutfp))
Пример #17
0
    def test_align(self):
        """Test method :meth:`plugins.enhancedstring.EnhancedString.align`

        **Tested:**

        - Center alignment works properly.
        - Right alignment works properly.
        - Left alignment workds properly.
        """
        str_ = enhancedstring.EnhancedString('a\nbcd\nefghi')
        str_.align('^')
        self.assertEqual(str(str_), '  a\n bcd\nefghi')
        str_.align('>')
        self.assertEqual(str(str_), '    a\n  bcd\nefghi')
        str_.align('<')
        self.assertEqual(str(str_), 'a\nbcd\nefghi')
Пример #18
0
def run():
    """Execute the challenges.044e module."""
    # Process the input.
    input_fp = os.path.join(cfg.input_dir, '044e_example_input.txt')
    with open(input_fp, 'r') as input_file:
        input = input_file.read()
    input = input.replace('\n', ' ')  ## newline characters become spaces
    input = es.EnhancedString(input)
    delimiters = '. ! ?'.split()
    sentences = [sentence.strip() for sentence in input.split(delimiters)]
    longest = max(sentences, key=lambda x: x.nwords)
    longwords = [word for word in longest.words if len(word) > 4]
    # Print the results.
    print("This is the complete input:")
    print(input, end='\n\n')
    print("Longest sentence in the input, with", longest.nwords, "words:")
    print(longest, end='\n\n')
    print("Words in this sentence longer than four characters:")
    print(longwords)
Пример #19
0
    def test_words(self):
        """Test property :meth:`plugins.enhancedstring.EnhancedString.words`

        **Tested:**

        - The enhanced string is correctly split in a list of enhancedstrings for each word.
        """
        s1 = enhancedstring.EnhancedString("This string has multiple words!")
        result = s1.words
        expected = [
            enhancedstring.EnhancedString("This"),
            enhancedstring.EnhancedString("string"),
            enhancedstring.EnhancedString("has"),
            enhancedstring.EnhancedString("multiple"),
            enhancedstring.EnhancedString("words!"),
        ]
        self.assertEqual(result, expected)
Пример #20
0
def run():
    """Execute the challenges.016e module."""
    str_ = estr.EnhancedString(utils.get_input("Input string: "))
    chars = utils.get_input("Characters to remove: ")
    str_.remove(chars)
    print("Result: {}".format(str_))
Пример #21
0
def run():
    """Execute the challenges.041e module."""
    text = utils.get_input("Enter a sentence > ")
    framed = es.EnhancedString(text).frame_with_ascii()
    print(framed)