〜43k行のtxtファイルを変更しようとしています。コマンド* Nsetがファイルに与えられた後、そのコマンドに続くすべての行を抽出して保存し、ファイル内の次の*コマンドに到達すると停止する必要があります。各コマンドの後には、異なる数の行と文字があります。例えば、ここでファイルのサンプル一部です:ファイル間で見出しの間の行を抽出する
*Nset
1, 2, 3, 4, 5, 6, 7,
12, 13, 14, 15, 16,
17, 52, 75, 86, 92,
90, 91, 92 93, 94, 95....
*NEXT COMMAND
blah blah blah
*Nset
numbers
*Nset
numbers
*Command
irrelevant text
コード私は必要な数字が2 *数Nsetの間に存在しないとき、私は現在、作品を持っています。 1つの* Netsが他の番号に続くとき、それはそのコマンドと進行する行を一緒にスキップして、なぜ私は理解できません。次のコマンドが* Nsetでなければ、次のコマンドを見つけて、データを完璧に引き出す。
import re
# read in the input deck
deck_name = 'master.txt'
deck = open(deck_name,'r')
#initialize variables
nset_data = []
matched_nset_lines = []
nset_count = 0
for line in deck:
# loop to extract all nset names and node numbers
important_line = re.search(r'\*Nset,.*',line)
if important_line :
line_value = important_line.group() #name for nset
matched_nset_lines.insert(nset_count,line_value) #name for nset
temp = []
# read lines from the found match up until the next *command
for line_x in deck :
if not re.match(r'\*',line_x):
temp.append(line_x)
else :
break
nset_data.append(temp)
nset_count = nset_count + 1
私はPython 3.5を使用しています。助けてくれてありがとう。
'* *'で始まる行の先頭には、常に*コマンドがありますか? –
@ juanpa.arrivillaga、はい。いろいろなコマンドがありますが、それぞれが "*"の直前です。そして次の行は数字です。 –
これはまったく関係ありますか? https://stackoverflow.com/questions/25943000/finding-a-word-between-two-words-that-will-not-match-if-the-closing-word-occurs –