提问人:shivakumar 提问时间:9/3/2023 最后编辑:shivakumar 更新时间:9/3/2023 访问量:32
在 python 中使用 readlines() 和 split() 方法识别和提取其相邻单词
Identifying and extraction of its adjacent word from using readlines() and split() method in python
问:
想要执行以下操作。
步骤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)
代码未识别目标单词。 提前致谢
答:
0赞
CtrlZ
9/3/2023
#1
也许您的数据与问题中显示的不完全相同。
不过,您可以简化代码:
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
评论