在具有行索引的模式后插入新字符串并写入新的fi

2024-07-04 08:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个python的新手,我已经通过多个python帖子、教程网站和源代码文档来解决我的问题,但是,我还没有完全做到!你知道吗

我要做的是:我有一个包含多行的文本文件,我首先查找从一个“MARKERSTRING”事件到另一个事件的标记文本块。”MARKERSTRING”在文本中多次出现,但只有少数在块中有“TAILSTRING”。如果找到了,那么我想在同一块中最后出现的字符串“BODY”下面添加一个新行(“newstring”)。你知道吗

我想将所有行保留到一个新文件中,并在给定的索引“BODY”(块中最后一次出现)处插入新字符串

我的文本文件的内容如下所示:

Multiple lines with some other text

MARKERSTRING SOMESTRING SOME OTHER STRING #

BODY A B C
BODY V G H
BODY Y U I

TAILSTRING X1 Y
TAILSTRING X2 Y


MARKERSTRING SOMESTRING SOME OTHER STRING # 

### #Although I want to append this to my file I dont want to process my #function through this as it does not have "TAILSTRING"

BODY B C
BODY V G H J
BODY Y U I

### #But want this block:

MARKERSTRING SOMESTRING SOME OTHER STRING #

BODY B C
BODY V G H J


TAILSTRING X1 Y
TAILSTRING X2 Y


Multiple lines with some other text

结束

我的问题如下:

  1. 获取索引并插入新字符串的函数只返回第一次出现的字符串。这可能是return语句的位置有问题,但是如果缩进得更多,它会抱怨“UnboundLocalError”。如果我使用“yield”函数,那么它将返回一个对象。我想在这个函数中写入新字符串

  2. 第二部分查找“MARKERSTRING”,将所有行附加到缓冲区,然后调用我的函数,不停地多次附加行,而不插入新字符串。这可能是因为我开始在for循环中寻找所需的模式,for循环获取文件中的每一行。

在不将每一行附加到for循环中的情况下,它们是一种更好的方法吗?你知道吗

像这样:

import re
from operator import itemgetter
import itertools


### The Function #########
def myfunc(filename):
    highest = None
    for cnt, line in enumerate(filename):

        if line.startswith("BODY "):
            bline = line.split()

            highest = cnt

        if line.startswith("TAIL"):
            lpline = line.split()
            print(lpline)
            newline = "BOND", lpline[2], lpline[4]

            newstring = ' '.join((str(x)) for x in newline)

            bline.insert(highest + 1, newstring) ##This doesnt insert
            return bline

### The "Markerstring" finder snippet: Keeps iterating over all lines #####

filename = open("input.txt").readlines()
outfilename = open("result.txt", 'w+')
buffer = []
keepCurrentSet = True
for line in filename:
    buffer.append(line)
    if (line.startswith('MARKERSTRING '):
        if keepCurrentSet:
            outfilename.write("".join(buffer))

            myfunc(filename)

预期结果:

Multiple lines with some other text


MARKERSTRING SOMESTRING SOME OTHER STRING #

BODY A B C
BODY V G H
BODY Y U I
BODY X1 Y     #Inserted line = newstring
BODY X2 Y     #Inserted line = newstring


TAILSTRING X1 Y
TAILSTRING X2 Y


MARKERSTRING SOMESTRING SOME OTHER STRING # 

### #Although I want to append this to my file I dont want to process my #function through this as it does not have "TAILSTRING"

BODY B C
BODY V G H J
BODY Y U I


### #But want this block:

MARKERSTRING SOMESTRING SOME OTHER STRING #


BODY B C
BODY V G H J
BODY X1 Y        #Inserted line = newstring
BODY X2 Y        #Inserted line = newstring

TAILSTRING X1 Y
TAILSTRING X2 Y

Multiple lines with some other text

END

Tags: to字符串stringlinebodysomethisother
1条回答
网友
1楼 · 发布于 2024-07-04 08:27:42

我说不出你为什么没有得到你想要的结果。通常,更改或修改一两行可以解决问题。你知道吗

然而,我想出了一个我认为可行的解决方案。你知道吗

编辑:在评论部分(以下)回答您的问题

_, params = line.split(maxsplit = 1)

对于maxsplit值1,这将拆分为2项。'.'是一个占位符,用于获取(并忽略)第一个拆分项TAILSTRING。分割的第二项(X1 YX2 Y)被分配给params。你知道吗

稍后我还要确定,主体X1 Y1还没有出现在我正在查看的MARKERSTRING块中

要实现这一点,需要修改代码。你知道吗

fin = open('f01.txt', 'r')
fout = open('temp.txt', 'w')

buffer = []
idx = 0

for line in fin:
    line = line.rstrip()
    buffer.append(line)
    if line.startswith('MARKERSTRING'):
        for item in buffer:
            fout.write(item + "\n")
        buffer = []
        idx = 0
        # continue because don't want to increment idx at bottom of loop
        # idx should be 0 for this iteration
        continue
    elif line.startswith('BODY'):
        max_body_idx = idx
    elif line.startswith('TAILSTRING'):
        _, params = line.split(maxsplit = 1)
        buffer.insert(max_body_idx+1, 'BODY ' + params)
        max_body_idx += 1
    idx += 1

fin.close()

# print out last record
for item in buffer:
    fout.write(item + "\n")

fout.close()

相关问题 更多 >

    热门问题