targeting words in a line of text

305 Views Asked by At

I have identified a line in a text file that looks like this:

FLAGS                    = WORD1 WORD2 WORD3

I am reading several files in which the number of words can vary from 0 to a maximum of 3.

I'm using this code:

flag_FLAG = 0
for i in range(len(materialfile)):
    if  "FLAG" in materialfile[i] and "=" in materialfile[i]:
        line_FLAG = i
        flag_FLAG = 1
        
    if flag_FLAG == 1:
        
        temp = materialfile[line_FLAG].split(" ")
        for elem in temp:
            if is_word(elem):
                flags = str(elem)

unfortunately this way I only get one word (the last one). "is_word" is a function that i creat:

def is_word(s):
    try:
        str(s)
        return True
    except ValueError:
        return False

I would like to get all the words as targets. I hope I have been clear.

2

There are 2 best solutions below

1
Samwise On

You want a nested loop, e.g.:

materialfile = [
    "FLAGS                    = WORD1 WORD2 WORD3",
]

flags = [
    flag
    for line in materialfile if "FLAGS" in line and "=" in line
    for flag in line.split(" = ")[1].split() if flag
]

print(flags)  # ['WORD1', 'WORD2', 'WORD3']

Hard to say whether this exact code will work with your actual file, since you didn't provide a sample file, but hopefully this gets you pointed in the right direction.

Note that your is_word function does nothing since these are already strings and will hence always convert to str() as a no-op without raising an exception. The if flag in the above comprehension will filter out values of flag that are empty (e.g. if you had a line like FLAGS = ).

2
Simone Panico On

I solved in this way:

for i in range(len(materialfile)):
    if  "FLAGS" in materialfile[i] and "="  in materialfile[i]:
        line_flag = i
        flag_flag = 1
if flag_flag == 1:
    flags = materialfile[line_flag].split(" = ")[1].split()

I don't know if this is an elegant way but it seems to work. Thanks