How to generate a lists of lists or nested from user input while outputting amount of times a word is stated?

Viewed 68

So far I have been able to create a function that asks the user to type a message and when the user inputs a message for example (nice day today #running #marathon) python outputs [running marathon]. However when it comes to the 2nd function under the output I want to create a lists of lists and how many times the particular word is said. A prime example would be input="Nice day #running #10k #power #running" and the final output would be [running,10k, power, running] and [[running,2],[10k,1],[power,1]]. I know I have to create a new list and use the result function.

import sys

def labeled():
 while(True):
    result = input("Enter a message or type q to end:")
    lstA =[]
    if result =='q':
        break
        print(lstA)
    else:
        for i in result.split():
            if "#" in i:
                lstA.append(i[1:])
                continue
        print(lstA)
                
def tabulated():
new_l=[]
result=[]

labeled()
tabulated()
3 Answers

UPDATED: If you want your tabulated() function to call your labeled function, you have a couple of different options for structuring your code:

Option 1: The labeled() function only queries the user once, then both prints and returns the resulting lstA. The tabulated() function calls the labeled() function, gets the returned output and processes it into the desired list of lists:

def labeled():
    lstA = []
    result = input("Enter a message or type q to end: ")
    if result == "q":
        return False
    for i in result.split():
        if "#" in i:
            lstA.append(i[1:])
    print(f'labeled output: {lstA}')
    return lstA

def tabulated():
    dic = {}
    for item in labeled():
        if item not in dic:
            dic[item] = 1
        else:
            dic[item] += 1
    list_of_lists = [[a,b] for a,b in dic.items()]
    print(list_of_lists)

tabulated()

#output:
Enter a message or type q to end: Nice day #running #10k #power #running
labeled output: ['running', '10k', 'power', 'running']
[['running', 2], ['10k', 1], ['power', 1]]

Option 2: The labeled() function queries the user multiple times as per your code. It not only prints lstA each time, but also appends each lstA into an aggregate list of lists. When the while loop is exited, it returns this aggregate list. When the tabulated function() calls the labeled function, it reads through the aggregate list item by item (line by line) and prints a desired list_of_list output for each line that the user had entered.

def labeled():
    aggregate_list = []
    while(True):
        lstA = []
        result = input("Enter a message or type q to end: ")
        if result =='q':
            break
        else:
            for i in result.split():
                if "#" in i:
                    lstA.append(i[1:])
            print(f'labeled output: {lstA}')
            aggregate_list.append(lstA)
    return aggregate_list

def tabulated():
    for sentence in labeled():
        dic = {}
        for item in sentence:
            if item not in dic:
                dic[item] = 1
            else:
                dic[item] += 1
        list_of_lists = [[a,b] for a,b in dic.items()]
        print(list_of_lists)

tabulated()

#output:
Enter a message or type q to end: Nice day #running #10k #power #running
labeled output: ['running', '10k', 'power', 'running']
Enter a message or type q to end: Great to #see #you and #see #your #dad
labeled output: ['see', 'you', 'see', 'your', 'dad']
Enter a message or type q to end: q
[['running', 2], ['10k', 1], ['power', 1]]
[['see', 2], ['you', 1], ['your', 1], ['dad', 1]]

Try this:

import sys

def labeled():
 while(True):
    result = input("Enter a message or type q to end:")
    lstA = []
    if result =='q':
        break
        print(lstA)
    else:
        for i in result.split():
            if "#" in i:
                lstA.append(i[1:])
                continue
        dictofwords = {}
        for i in lstA:
            if not i in dictofwords:
                dictofwords[f'{i}'] = 1
            else:
                dictofwords[f'{i}'] = dictofwords[f'{i}'] + 1
        print(lstA)
        print(dictofwords)

def tabulated():
    new_l=[]
    result=[]

    labeled()
    tabulated()

I didn't actually make a list of lists, but rather a dictionary. I then iterated over the first list, and -

  • If the element did not appear in the dictionary, add it with the corresponding value of "1"
  • If the element did appear in the dictionary, simply increase its corresponding value

Probably something like this:

sample = "Nice day #running #10k #power #running"

def process_input(string, key_char = "#"):

    # Creating a clean list of keywords by a given target character.
    base_list = [i.replace(f"{key_char}", "") for i in string.split(" ") if i[0] == f"{key_char}"]

    # We can use the list.count() function on a set of keywords
    # to return the instance of each word within a given string.
    word_count_list = [[w, base_list.count(w)] for w in set(base_list)]

    return base_list, word_count_list

Output of process_input(sample):

(['running', '10k', 'power', 'running'],
 [['power', 1], ['running', 2], ['10k', 1]])
Related