Python Forum
General Programming Question with Dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
General Programming Question with Dictionary
#11
I never heard of inflect before, and I will probably never need it, but it is interesting.

I don't think I will ever have a good grasp of re!

Personally, I would make a dictionary of dictionaries for authors and books. Make the first key the author name and the value a dictionary. Save it to json.

The sub dictionary keys would be the book names and the values any details.

Also, you could split the Written Time and Published Time to make things easier.

If you simply entered all numbers as numbers, the solution would be very simple.

Nevertheless, it was interesting for me, made a change from solving sudokus!

This works for me, I hope it works for you too, or at least gives you some ideas!

def myApp():
    import re
    import inflect
    import json

    dict_keys = ['Book Number', 'Book Names', 'Number of Pages', 'Time Written or Published', 'Authors']
    book_nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
    book_names = ['For Whom the Bell Tolls', 'Brave New World', 'Nineteen Eighty-Four',
                  'The Sound and the Fury', 'Gone with the Wind', "Lady Chatterley's Lover",
                  'The Hound of the Baskervilles', 'I Am Number 4', 'The Great Gatsby',
                  'The War of the Worlds', 'The Lord of the Rings', 'Martin Eden', 'On the Road',
                  "A Room of One's Own", 'Lord Jim', 'Manhattan Transfer', "Sophie's Choice",
                  'The Catcher in the Rye', 'No Orchids For Miss Blandish',
                  'The Origins of Totalitarianism The Burden of Our Time', 'Fahrenheit 451']
    book_pages = [None, 311, 328, 326, '1037 (first edition), 1024 (Warner Books Paperback)',
                   None, None, 440, None, 287, 'original manuscripts, which total 9,250 pages',
                   None, 320, 172, None, None, 562, 234, None, 704, 256]
    book_time = [1940, 1932, 1949, 1929, 1936, 1928, '1901–02', 2009, 1925, 1898, '1954–55',
                 1909, 1957, 1929, 1900, 1925, 1979, 1951, 1939, 1951, 1953]
    book_author = ['Ernest Hemingway', 'Aldous Huxley', 'George Orwell', 'William Faulkner',
                   'Margaret Mitchell', 'D.H. Lawrence', 'Arthur Conan Doyle', 'Jobie Hughes',
                   'James Frey', 'F. Scott Fitzgerald', 'H.G. Wells', 'J.R.R. Tolkien', 'Jack London',
                   'Jack Kerouac', 'Virginia Woolf', 'Joseph Conrad', 'John Dos Passos',
                   'William Styron', 'J.D. Salinger', 'James Hadley Chase', 'Hannah Arendt', 'Ray Bradbury']

    values = [book_nums, book_names, book_pages, book_time, book_author]

    # make the dictionary from your data
    book_dict1 = {dict_keys[i]:values[i] for i in range(len(dict_keys))}
    # have a look at the dictionary
    for key in book_dict1.keys():
        print(key)
        print(book_dict1[key])

    numname = inflect.engine()

    # in case you want a list again
    def string2list(astring):
        newstring = astring.replace('[', '').replace(']', '').replace('\'', '')
        mylist = newstring.split(', ')
        return mylist

    # make the first letter of the number word a capital letter
    def capitalise(adict):
        for key in adict.keys():
            word = adict[key]
            firstletter = word[0].upper()
            newword = firstletter + word[1:]
            adict[key] = newword
        return adict

    # re.sub(pattern, repl, string, count=0, flags=0)
    def listnums2words(alist):
        mystring = str(alist)
        nums = re.findall(r'\d+', mystring)
        if len(nums) == 0:
            return alist
        numwords = {n:numname.number_to_words(n) for n in nums}
        caps_dict = capitalise(numwords)
        for key in caps_dict.keys():
            changed = re.sub(key, caps_dict[key], mystring, count=0)
            mystring = changed
        result = mystring.replace('None', 'Zero')
        return result
            
    for key in book_dict1.keys():
        mylist = book_dict1[key]
        # newvalue may now be a string not a list
        newvalue = listnums2words(mylist)
        book_dict1[key] = newvalue

    # if you want a list as value
    for key in book_dict1.keys():
        print(key)
        print(book_dict1[key])
        print(type(book_dict1[key]))
        if not type(book_dict1[key]) == list:
            newlist = string2list(book_dict1[key])
            book_dict1[key] = newlist
                    
    for key in book_dict1.keys():
        print(key)
        print(book_dict1[key])

    mypath = '/home/pedro/temp/books_data_json.json'
    with open(mypath, 'w') as json_file:
        json.dump(book_dict1, json_file)
        print('data saved to', mypath)

    print('All done!')
giddyhead likes this post
Reply
#12
(Jan-09-2022, 12:39 AM)Pedroski55 Wrote: I never heard of inflect before, and I will probably never need it, but it is interesting.

I don't think I will ever have a good grasp of re!

Personally, I would make a dictionary of dictionaries for authors and books. Make the first key the author name and the value a dictionary. Save it to json.

The sub dictionary keys would be the book names and the values any details.

Also, you could split the Written Time and Published Time to make things easier.

If you simply entered all numbers as numbers, the solution would be very simple.

Nevertheless, it was interesting for me, made a change from solving sudokus!

This works for me, I hope it works for you too, or at least gives you some ideas!

def myApp():
    import re
    import inflect
    import json

    dict_keys = ['Book Number', 'Book Names', 'Number of Pages', 'Time Written or Published', 'Authors']
    book_nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
    book_names = ['For Whom the Bell Tolls', 'Brave New World', 'Nineteen Eighty-Four',
                  'The Sound and the Fury', 'Gone with the Wind', "Lady Chatterley's Lover",
                  'The Hound of the Baskervilles', 'I Am Number 4', 'The Great Gatsby',
                  'The War of the Worlds', 'The Lord of the Rings', 'Martin Eden', 'On the Road',
                  "A Room of One's Own", 'Lord Jim', 'Manhattan Transfer', "Sophie's Choice",
                  'The Catcher in the Rye', 'No Orchids For Miss Blandish',
                  'The Origins of Totalitarianism The Burden of Our Time', 'Fahrenheit 451']
    book_pages = [None, 311, 328, 326, '1037 (first edition), 1024 (Warner Books Paperback)',
                   None, None, 440, None, 287, 'original manuscripts, which total 9,250 pages',
                   None, 320, 172, None, None, 562, 234, None, 704, 256]
    book_time = [1940, 1932, 1949, 1929, 1936, 1928, '1901–02', 2009, 1925, 1898, '1954–55',
                 1909, 1957, 1929, 1900, 1925, 1979, 1951, 1939, 1951, 1953]
    book_author = ['Ernest Hemingway', 'Aldous Huxley', 'George Orwell', 'William Faulkner',
                   'Margaret Mitchell', 'D.H. Lawrence', 'Arthur Conan Doyle', 'Jobie Hughes',
                   'James Frey', 'F. Scott Fitzgerald', 'H.G. Wells', 'J.R.R. Tolkien', 'Jack London',
                   'Jack Kerouac', 'Virginia Woolf', 'Joseph Conrad', 'John Dos Passos',
                   'William Styron', 'J.D. Salinger', 'James Hadley Chase', 'Hannah Arendt', 'Ray Bradbury']

    values = [book_nums, book_names, book_pages, book_time, book_author]

    # make the dictionary from your data
    book_dict1 = {dict_keys[i]:values[i] for i in range(len(dict_keys))}
    # have a look at the dictionary
    for key in book_dict1.keys():
        print(key)
        print(book_dict1[key])

    numname = inflect.engine()

    # in case you want a list again
    def string2list(astring):
        newstring = astring.replace('[', '').replace(']', '').replace('\'', '')
        mylist = newstring.split(', ')
        return mylist

    # make the first letter of the number word a capital letter
    def capitalise(adict):
        for key in adict.keys():
            word = adict[key]
            firstletter = word[0].upper()
            newword = firstletter + word[1:]
            adict[key] = newword
        return adict

    # re.sub(pattern, repl, string, count=0, flags=0)
    def listnums2words(alist):
        mystring = str(alist)
        nums = re.findall(r'\d+', mystring)
        if len(nums) == 0:
            return alist
        numwords = {n:numname.number_to_words(n) for n in nums}
        caps_dict = capitalise(numwords)
        for key in caps_dict.keys():
            changed = re.sub(key, caps_dict[key], mystring, count=0)
            mystring = changed
        result = mystring.replace('None', 'Zero')
        return result
            
    for key in book_dict1.keys():
        mylist = book_dict1[key]
        # newvalue may now be a string not a list
        newvalue = listnums2words(mylist)
        book_dict1[key] = newvalue

    # if you want a list as value
    for key in book_dict1.keys():
        print(key)
        print(book_dict1[key])
        print(type(book_dict1[key]))
        if not type(book_dict1[key]) == list:
            newlist = string2list(book_dict1[key])
            book_dict1[key] = newlist
                    
    for key in book_dict1.keys():
        print(key)
        print(book_dict1[key])

    mypath = '/home/pedro/temp/books_data_json.json'
    with open(mypath, 'w') as json_file:
        json.dump(book_dict1, json_file)
        print('data saved to', mypath)

    print('All done!')

Thank you for your help. I Still learning the process and this is my first time trying dictionaries. Once again. Thanks
Reply
#13
I only tinker with this stuff, by no means and expert.

I modified myApp() this morning, now it saves and displays the json nicely formatted, all the values are lists.

The annoying thing with inflect is, it always returns thousands followed by a comma, except when there are no hundreds, like "one thousand, " then the hundreds. That messed up my attempt to reinstate the string as a list.

If you want I can post it. I'm sure no one else is interested.

But like I said, I would go for a dictionary of dictionaries, keep numbers as numbers and strings as strings, that makes things very simple.

Was fun for me!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python can - general question caslor 0 1,120 Jul-14-2022, 05:21 PM
Last Post: caslor
  a general question barryjo 5 1,521 Feb-01-2022, 10:12 PM
Last Post: Gribouillis
Big Grin General programming question (input string)[ jamie_01 2 1,607 Jan-08-2022, 12:59 AM
Last Post: BashBedlam
  Question about formula implementation in general format Alienspecimen 0 1,668 Mar-01-2021, 08:39 PM
Last Post: Alienspecimen
  General list size question to solve problem Milfredo 3 2,361 Sep-27-2020, 08:42 AM
Last Post: Milfredo
  New to programming, loop question tomyan 1 1,646 Sep-25-2020, 04:32 PM
Last Post: Larz60+
  General Listbox question. Milfredo 4 2,160 Sep-06-2020, 07:36 PM
Last Post: Milfredo
  Dictionary question DrZ 2 1,667 Jul-29-2020, 08:53 PM
Last Post: DrZ
  General question about serialization/deserialization in python local 1 1,850 Jan-28-2020, 04:35 AM
Last Post: Larz60+
  General Programming Question Qui_Ten 1 2,190 Jan-14-2019, 11:15 AM
Last Post: steve_shambles

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020