0

I am trying to locate words that contains certain string inside a list of lists in python, for example: If I have a list of tuples like:

the_list = [
    ('Had denoting properly @T-jointure you occasion directly raillery'), 
    ('. In said to of poor full be post face snug. Introduced imprudence'),
    ('see say @T-unpleasing devonshire acceptance son.'),
    ('Exeter longer @T-wisdom gay nor design age.', 'Am weather to entered norland'),
    ('no in showing service. Nor repeated speaking', ' shy appetite.'),
    ('Excited it hastily an pasture @T-it observe.', 'Snug @T-hand how dare here too.')
    ]

I want to find a specific string that I search for and extract a complete word that contains it, example

for sentence in the_list:
    for word in sentence:
        if '@T-' in word:
            print(word)

   
The Dan
  • 1,408
  • 6
  • 16
  • 41

3 Answers3

0
import re

wordSearch = re.compile(r'word')
for x, y in the_list:
    if wordSearch.match(x):
        print(x)
    elif wordSearch.match(y):
        print(y)
Kyle Hurst
  • 252
  • 2
  • 6
  • In this case, "x" and "y" are the strings I want to search for inside the words (like '@T-'), right? – The Dan Feb 26 '21 at 20:42
  • well, your tuple is ("this", "that"), so for each iteration, x = this and y = that. Your match will go against each item and then you only deal with the results you want. – Kyle Hurst Mar 01 '21 at 18:36
0

You could use list of comprehension on a flattened array of yours:

from pandas.core.common import flatten

[[word for word in x.split(' ') if '@T-' in word] for x in list(flatten(the_list)) if '@T-' in x]
#[['@T-jointure'], ['@T-unpleasing'], ['@T-wisdom'], ['@T-it'], ['@T-hand']]

Relevant places: How to make a flat list out of list of lists? (specifically this answer), Double for loop list comprehension.

My Work
  • 2,143
  • 2
  • 19
  • 47
0

you would need to use re for this task

import re

a = re.search("@(.*?)[\s]",'Exeter longer @T-wisdom gay nor design age.')

a.group(0)

Note : you need to account for the Nonetype else it will throw and error

for name in the_list:
try:
    
    if isinstance(name,(list,tuple)):
        for name1 in name:
            result = re.search("@(.*?)[\s]",name1)
            print(result.group(0))
    else:
        
        result = re.search("@(.*?)[\s]",name)
        print(result.group(0))
    

except:
    pass
omar magdi
  • 36
  • 3