1

I have two lists of words, one with keywords (nouns) fom a text and one with all the adj + noun pairings from the same text. I need to merge the lists into one that only contains the keyword nouns plus the paired adjective (if there is one) ex:

keywords:{apple, house, sword}
noun_adj:{red apple, fast car, big house, new phone, sharp sword}
result:{red apple, big house, sharp sword}

I am new to python and have been looking for an answer for a while, but I dont know what to search for. The 2 lists are output and noun_adj_pairs.

Stama
  • 11
  • 2

2 Answers2

3

Assuming these are strings inside of your lists...

Using list comprehension

keywords = ['apple', 'house', 'sword']
noun_adj = ['red apple', 'fast car', 'big house', 'new phone', 'sharp sword']

result = [n for n in noun_adj for k in keywords if k in n]

Or a nested for loop

keywords = ['apple', 'house', 'sword']
noun_adj = ['red apple', 'fast car', 'big house', 'new phone', 'sharp sword']

result = []
for n in noun_adj:
    for k in keywords:
        if k in n:
            result.append(n)

Edited as per Corralien's comment, thank you.

StevieW
  • 163
  • 6
  • 1
    Great answer. +1 but put the list comprehension in first. It's more pythonic. – Corralien Aug 02 '21 at 07:57
  • It's worth mentioning that the built-in function 'x in y' works based on the characters instead of the words. Therefore it will produce true values when the keyword is part of the noun or adjective words. For example, the result for the 'good housekeeper' will be true. ([More information](https://stackoverflow.com/a/36558717/9346942)) – Parsa Abbasi Aug 02 '21 at 09:22
0

I separated adj and noun using split() function. After that, only Noun examined through the for statement.

result = set()
for i in noun_adj:
    k = i.split()
    if k[1] in keyword: result.add(i)
Hailey
  • 302
  • 1
  • 7