如何在自动更新的文件中获取文本的最后一次出现

编程入门 行业动态 更新时间:2024-10-28 19:20:02
如何在自动更新的文件中获取文本的最后一次出现 - python?(How can I get the last occurence of a text in a file that is automatically updated - python?)

[问题]

在使用新数据自动刷新的文件中,我想得到: - 与最新字符串occcurence对应的数字。 例如,在上面的虚拟示例中,我想要获取: - 最后出现stringZ ,然后是该文本中的数字。 实际上我想取:[99]

File sample: ".... Manually launch test 1 stringX Manually launch test 2 stringY Manually launch test 3 stringW Manually launch test 10 stringZ ................ Manually launch test 200 stringX Manually launch test 300 stringY Manually launch test 77 stringW Manually launch test 99 stringZ "

[码]

tempFile = open(fileName, "r") while True: fileContent = str(tempFile.readlines()) print temp latestOccurence= re.search("(.*)stringZ",fileContent ).group(0) latestOccurence= re.search('([0-9])+',latestOccurence).group(0) print latestOccurence

[PROBLEM]

In a File that refreshes automatically with new data, I want to get: - the number that corresponds to latest string occcurence. For instance, in the dummy example below above I want to fetch: - last occurence of stringZ and afterwards the number inside that text. In practical terms I want to fetch: [99]

File sample: ".... Manually launch test 1 stringX Manually launch test 2 stringY Manually launch test 3 stringW Manually launch test 10 stringZ ................ Manually launch test 200 stringX Manually launch test 300 stringY Manually launch test 77 stringW Manually launch test 99 stringZ "

[CODE]

tempFile = open(fileName, "r") while True: fileContent = str(tempFile.readlines()) print temp latestOccurence= re.search("(.*)stringZ",fileContent ).group(0) latestOccurence= re.search('([0-9])+',latestOccurence).group(0) print latestOccurence

最满意答案

regex = re.compile(r'Manually launch test ([0-9]+) stringZ') while True: latestOccurrence = None with open(fileName) as tempFile: for line in tempFile: if "stringZ" in line: match = regex.match(line) if match: latestOccurrence = int(match.group(1)) # do something with latestOccurrence here? time.sleep(1) regex = re.compile(r'Manually launch test ([0-9]+) stringZ') while True: latestOccurrence = None with open(fileName) as tempFile: for line in tempFile: if "stringZ" in line: match = regex.match(line) if match: latestOccurrence = int(match.group(1)) # do something with latestOccurrence here? time.sleep(1)

更多推荐

本文发布于:2023-07-20 12:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1199604.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自动更新   文本   文件   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!