使用Python中的readlines()和split()方法识别和提取其相邻单词

问题描述 投票:0回答:1

想要执行以下操作。

步骤 1 -> 从 *.k 文件中想要读取所有行。 步骤 2 -> 从此文件中识别特定单词(例如:“endtim”)。 步骤3 -> 邻接词t0“endtim”识别。(这里邻接词 -> endcyc)
步骤 4 -> 存储并写入新文件。

文件 ---> 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)

代码无法识别目标单词。 预先感谢

python split readlines
1个回答
0
投票

也许您的数据与问题中显示的不完全一样。

不过你可以简化你的代码:

with open('tshell.k') as data:
    for line in data:
        tokens = line.strip().split()
        try:
            i = tokens.index('endtim')
            print(tokens[i+1])
        except (ValueError, IndexError):
            pass
© www.soinside.com 2019 - 2024. All rights reserved.