读取一行将其存储在变量中,然后读取另一行并返回到第一行。Python 2
这是一个棘手的问题,我读过很多关于它的帖子,但我一直没能让它起作用 我有一个大文件。我需要一行一行地读,一旦我读到一行形式为“总计是:(任何十进制数)”,就用这个字符串将数字保存在一个变量中。如果数字大于40.0,那么我需要找到读取一行将其存储在变量中,然后读取另一行并返回到第一行。Python 2,python,regex,file,line,python-2.x,Python,Regex,File,Line,Python 2.x,这是一个棘手的问题,我读过很多关于它的帖子,但我一直没能让它起作用 我有一个大文件。我需要一行一行地读,一旦我读到一行形式为“总计是:(任何十进制数)”,就用这个字符串将数字保存在一个变量中。如果数字大于40.0,那么我需要找到Total行上方的第四行(例如,如果Total行是第39行,那么这一行就是第35行)。此行的格式为(数字)。(空格)(子字符串)。最后,我需要解析这个子字符串并对其进行进一步处理 这是一个输入文件的示例: 许多我们不关心的行 很多我们不关心的台词 ... 1.Hi45 人
Total
行上方的第四行(例如,如果Total
行是第39行,那么这一行就是第35行)。此行的格式为(数字)。(空格)(子字符串)
。最后,我需要解析这个子字符串并对其进行进一步处理
这是一个输入文件的示例:
许多我们不关心的行
很多我们不关心的台词
...
1.Hi45
人:呜呜呜呜呜呜呜呜
空白
呜呜呜呜呜呜呜呜
总计为:(*此处为十进制数*)
布拉布拉
空白
...
更多我们不关心的线路
再多排几行,然后
我们又得到了
2.如何144
人:呜呜呜呜呜呜呜呜
空白
呜呜呜呜呜呜呜呜
总计为:(*此处为十进制数*)
布拉布拉
空白
我尝试了很多方法,包括使用re.search()
方法从我需要关注的每一行中获取我需要的内容
这是我从另一个stackoverflow问答中修改的代码:
重新导入
导入行缓存
number=“”
更高的_行=“”
找到了_行=“”
以open(“filename_with_many_lines.txt”)作为文件:
对于num,枚举中的行(文件,1):
searchObj=re.search(r'(\b全部\b)(\s)(\w+)(\:)(\s)(\d+。\d+),行)
如果搜索对象:
打印“这是联机的”,第行
打印“这是行号:”,num
var1=搜索对象组(6)
打印变量1
如果浮动(var1)>40.0:
number=num
高位线=数字-4
打印号码
打印更高的行
found_line=linecache.getline(“文件名_with_many_line.txt”,更高的_行)
打印“找到了”,找到了\u行
预期产出将是:
这是在线的总数是:45.5
这是电话号码:14857
14857
14853
找到了1。Hi145
这是在线的总数是:62.1
这是电话号码:14985
14985
14981
找到了2.144
如果所需的行始终比总数高出四行:
行,则可以将前面的行保持在有界范围内
如果添加新项目会导致项目超过其最大长度,则有界的deque
(具有最大长度的项目)将从另一侧丢弃项目。在本例中,我们将字符串附加到deque
的右侧,因此一旦deque
的长度达到4
,我们附加到右侧的每个新字符串将导致它从左侧丢弃一个字符串。因此,在for
循环开始时,deque
将包含当前行之前的四行,最早的行位于最左侧(索引0
)
事实上,提到的用例与我们的非常相似:
有界长度deques提供的功能类似于Unix中的tail
过滤器。它们还可用于跟踪仅关注最新活动的事务和其他数据池
如果所需的行始终比
总计为:
行高出四行,则可以将前面的行保持在有界状态
如果添加新项目会导致项目超过其最大长度,则有界的deque
(具有最大长度的项目)将从另一侧丢弃项目。在本例中,我们将字符串附加到deque
的右侧,因此一旦deque
的长度达到4
,我们附加到右侧的每个新字符串将导致它从左侧丢弃一个字符串。因此,在for
循环开始时,deque
将包含当前行之前的四行,最早的行位于最左侧(索引0
)
事实上,提到的用例与我们的非常相似:
有界长度deques提供的功能类似于Unix中的tail
过滤器。它们还可用于跟踪仅关注最新活动的事务和其他数据池
这会将以数字和点开头的行存储到名为
prevline
的变量中。仅当re.search
返回匹配对象时,才打印prevline
import re
with open("file") as aFile:
prevline = ""
for num, line in enumerate(aFile,1):
m = re.match(r'\d+\.\s*.*', line) # stores the match object of the line which starts with a number and a dot
if m:
prevline += re.match(r'\d+\.\s*(.*)', line).group() # If there is any match found then this would append the whole line to the variable prevline. You could also write this line as prevline += m.group()
searchObj = re.search(r'(\bTotal\b\s+\w+:\s+(\d+\.\d+))', line) # Search for the line which contains the string Total plus a word plus a colon and a float number
if searchObj: # if there is any
score = float(searchObj.group(2)) # then the float number is assigned to the variable called score
if score > 40.0: # Do all the below operations only if the float number we fetched was greater than 40.0
print "this is the line number: ", num
print "this is the line", searchObj.group(1)
print num
print num-4
print "found the", prevline
prevline = ""
输出:
this is on line Total is: 45.5
this is the line number: 8
8
4
found the 1. Hi45
this is on line Total is: 62.1
this is the line number: 20
20
16
found the 2. How144
这会将以数字和点开头的行存储到名为
prevline
的变量中。仅当re.search
返回匹配对象时,才打印prevline
import re
with open("file") as aFile:
prevline = ""
for num, line in enumerate(aFile,1):
m = re.match(r'\d+\.\s*.*', line) # stores the match object of the line which starts with a number and a dot
if m:
prevline += re.match(r'\d+\.\s*(.*)', line).group() # If there is any match found then this would append the whole line to the variable prevline. You could also write this line as prevline += m.group()
searchObj = re.search(r'(\bTotal\b\s+\w+:\s+(\d+\.\d+))', line) # Search for the line which contains the string Total plus a word plus a colon and a float number
if searchObj: # if there is any
score = float(searchObj.group(2)) # then the float number is assigned to the variable called score
if score > 40.0: # Do all the below operations only if the float number we fetched was greater than 40.0
print "this is the line number: ", num
print "this is the line", searchObj.group(1)
print num
print num-4
print "found the", prevline
prevline = ""
输出:
this is on line Total is: 45.5
this is the line number: 8
8
4
found the 1. Hi45
this is on line Total is: 62.1
this is the line number: 20
20
16
found the 2. How144
我建议对Blacklight Shining的帖子进行编辑,该帖子建立在其
deque
解决方案的基础上,但遭到拒绝,建议将其改为答案。下面,我将展示Blacklight的解决方案如何解决您的问题,如果您只是盯着它看一会儿的话
with open(filename, 'r') as file:
# Clear: we don't care about checking the first 4 lines for totals.
# Instead, we just store them for later.
previousLines = []
previousLines.append(file.readline())
previousLines.append(file.readline())
previousLines.append(file.readline())
previousLines.append(file.readline())
# The earliest we should expect a total is at line 5.
for lineNum, line in enumerate(file, 5):
if line.startswith('Total is: '):
prevLine = previousLines[0]
high_num = prevLine.split()[1] # A
score = float(line.strip("Total_is: ").strip("\n").strip()) # B
if score > 40.0:
# That's all! We've now got everything we need.
# Display results as shown in example code.
print "this is the line number : ", lineNum
print "this is the line ", line.strip('\n')
print lineNum
print (lineNum - 4)
print "found the ", prevLine
# Critical - remove old line & push current line onto deque.
previousLines = previousLines[1:] + [line]
我没有利用deque,但我的代码必须完成同样的任务。我不认为这是一个比其他任何一个更好的答案;我发布它是为了展示如何用一个非常简单的算法和简单的工具解决您试图解决的问题。(将阿维纳什巧妙的17行解决方案与我简化的18行解决方案进行比较。)
这种简化的方法不会让任何阅读代码的人觉得你像个向导,但它也不会意外地匹配中间行中的任何内容。如果你死心塌地想用正则表达式来处理你的行,那么只需修改行a和B。一般的解决方案仍然有效
警察局