Beginning
Line 2
Line 3
Line 4
Line 5
Line 6
End
试图通过第6行拉开第2行。不能这样做来拯救我的灵魂。 a是我正在搜索的已保存字符串。
b = re.findall(r'Beginning(.*?)End', a)
不给我一个东西,只是一个空白的b。我知道这是因为新行,但我如何检测并继续推进新行。我已经尝试过,不知道我确定如何使用MULTILINE或DOTALL。什么都没有改变。
如何让它将第2行到第6行放入b?
要添加,这将通过我需要执行此搜索和拉取技术的同一文件多次出现。我没有其他简单的方法来执行此操作,因为需要进一步查看第2-6行中的信息以获取将放入csv文件的数据。由于某些数据包含数小时且某些数据不包含小时数(又称“不可用”),因此我需要能够拉出并区分这两种情况。
答案 0 :(得分:0)
string = """Beginning
Line 2
Line 3
Line 4
Line 5
Line 6
End
"""
lines = string.splitlines()
answer = []
flag = False
for line in lines:
line = line.strip()
if not line: continue
if line == "Beginning":
flag = True
continue
if line == "End": flag = False
if not flag: continue
answer.append(line)
输出:
In [209]: answer
Out[209]: ['Line 2', 'Line 3', 'Line 4', 'Line 5', 'Line 6']
答案 1 :(得分:0)
您可以创建一个包含多行字符串,然后是起始行和结束行的函数。
def Function(string, starting_line, ending_line):
if "\n" in string: #Checks for whether or not string is mult-line
pass
else:
return "The string given isn't a multiline string!" #If string isn't multiline, then Function returns a string explaining that string isn't a multi-line string
if ending_line < starting_line: #Checks if ending_line < starting_line
return "ending_line is greater than starting_line!" #If ending_line < starting_line, then Function returns a string explaining that ending_line > starting_line
array = [] #Defines an array
for i in range(len(string)): #Loops through len(string)
if list(string)[i] = "\n": #Checks whether list(string)[i] = a new line
array.append(i) #Appends i to array
return string[array[starting_line - 1]::array[ending_line - 1]]
print(Function(a, 3, 7))
此代码应返回:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6