Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Detecting Unique Terms In A List Contained of Multiple Strings

example = ["duran duran sang wild boys in 1984", "wild boys don't remain forever wild", "who brought wild flowers","it was john krakauer who wrote in to the wild"]

How do I detect unique terms and put them in a list like this:

['duran', 'sang', 'wild', 'boys', 'in', '1984', "don't", 'remain', 'forever', 'who', 'brought', 'flowers', 'it', 'was', 'john', 
'krakauer', 'wrote', 'to', 'the']

My code:

def uniqueterms(a, d, e, f) :    
    b = a.split()
    c = [] `

    for x in b:
        if a.count(x) >= 1 and (x not in c):
            c.append(x)
    print((' '.join(c)).split(), end=' ')
    g = d.split()
    h = []

    for y in g:
        if d.count(y) >= 1 and (y not in h):
            h.append(y)
    print((' '.join(h)).split(), end=' ')
    i = e.split()
    j = []

    for z in i:
        if e.count(z) >= 1 and (z not in j):
            j.append(z)
    print((' '.join(j)).split(), end=' ')
    k = f.split()
    m = []

    for t in k:
        if f.count(t) >= 1 and (t not in m):
            m.append(t)
    print((' '.join(m)).split())

>>> uniqueterms(example[0], example[1], example[2], example[3])
['duran', 'sang', 'wild', 'boys', 'in', '1984'] ['wild', 'boys', "don't", 'remain', 'forever'] ['who', 'brought', 'wild', 'flowers'] ['it', 'was', 'john', 'krakauer', 'who', 'wrote', 'in', 'to', 'the', 'wild']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use string.split and python’s built-in set data structure:

def get_unique_words(text):
    return list(set(text.split()))

To handle a list of strings:

def get_unique_words_from_list_of_strings(str_list):
    return get_unique_words(' '.join(str_list))

To sort the resulting list:

words_in_order = sorted(unordered_list)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading