pythonsplitreadlines

Identifying and extraction of its adjacent word from using readlines() and split() method in python


Would like to perform following operations.

Step 1 -> From the *.k file would like to read all the lines. Step 2 -> Identifying specific word (Ex: "endtim") from this file. Step 3 -> Adjacent word t0 "endtim" identification.(Here Adjacent word -> endcyc)
Step 4 -> Storing and writing it into new file.

file ---> tshell.k

*KEYWORD
*TITLE
Simply Supported Square Plate: Out-of-Plane Vibration (thick shell mesh)
*CONTROL_IMPLICIT_EIGENVALUE
$#    neig    center     lflag    lftend     rflag    rhtend    eigmth    shfscl
        20       0.0         0       0.0         0       0.0         0       0.0
*CONTROL_IMPLICIT_GENERAL
$#  imflag       dt0    imform      nsbs       igs     cnstn      form
         1       0.0
*CONTROL_SHELL
$#  wrpang     esort     irnxx    istupd    theory       bwc     miter      proj
  20.00000         0         0         0         2         2         1
$# rotascl    intgrd    lamsht    cstyp6    tshell    nfail1    nfail4
       0.0         1
*CONTROL_TERMINATION
$#  endtim    endcyc     dtmin    endeng    endmas
  1.000000         0       0.0       0.0       0.0
with open("tshell.k", "r") as k_file:
    lines = k_file.readlines()

    for line in lines:
        words = line.split()
        print(words)

        target_word = "endtim"
        target_word_index = words.index(target_word)
        next_word = target_word_index + 1

        if next_word < len(words):
            next_word = words[next_word]
            print(next_word)

The code is not identifying the target word. Thanks in advance


Solution

  • Maybe your data are not exactly as shown in the question.

    You could simplify your code though:

    with open('tshell.k') as data:
        for tokens in map(str.split, data):
            try:
                # potential ValueError here if 'endtim' isn't in the token list
                i = tokens.index('endtim')
                # potential IndexError here when/if 'endtim' was the last item in the token list
                print(tokens[i+1])
            except (ValueError, IndexError):
                pass