There is a log file in txt format, which is constantly updated. And among the lines of this file, there is a template message that contains two numbers. How to implement the reading of these two numbers and write them into variables. For example

[I] [22:50:14] [01:50:14] [Client thread/INFO]: [CHAT] >>                                      [I] [22:50:19] [01:50:18] [Client thread/INFO]: [CHAT]              : 530 + 797 [I] [22:50:19] [01:50:18] [Client thread/INFO]: [CHAT]                        ,                             1  . 

That is, you need to select among the lines 530 + 797, and write the sum into a variable.

  • If my answer helped you, mark it, please, as adopted by pressing v under the tally counter - Sergey Nudnov

2 answers 2

 import re a = ["[I] [22:50:14] [01:50:14] [Client thread/INFO]: [CHAT] >>                                     ", "[I] [22:50:19] [01:50:18] [Client thread/INFO]: [CHAT]              : 530 + 797", "[I] [22:50:19] [01:50:18] [Client thread/INFO]: [CHAT]                        ,                             1  ."] for i in a: res = re.findall(r': (\d+) \+ (\d+)$', i) if res: print(sum(map(int, *res))) #1327 
  • 2
    Everything is so, just do not read the logs in the memory. Fraught. Analyze line by line, preferably with saving the last position in the config and the next launch of the analyzer - with checking the hash of the last line with the saved and continued. Or go to the beginning, if the log was otrotirotiro ... - Sergey Nudnov
  • How the author of the question will read the logs is a separate conversation. The answer was given to a specific question, and your comment is not to the address. - strawdog

As I noticed to the distinguished @strawdog in the comments to his answer, reading the logs as a whole in memory is not good, better is line by line. And the code in this case is easier to understand:

 import re # ΠšΠΎΠΌΠΏΠΈΠ»ΠΈΡ€ΡƒΠ΅ΠΌ regex ΠΏΠ΅Ρ€Π΅Π΄ использованиСм Π² Ρ†ΠΈΠΊΠ»Π΅ - экономим врСмя r_pattern = re.compile(': (\d+) \+ (\d+)$') # НС Π·Π°Π±Ρ‹Π²Π°Π΅ΠΌ ΡƒΠΊΠ°Π·Π°Ρ‚ΡŒ ΠΏΡ€Π°Π²ΠΈΠ»ΡŒΠ½ΡƒΡŽ ΠΊΠΎΠ΄ΠΈΡ€ΠΎΠ²ΠΊΡƒ Ρ„Π°ΠΉΠ»Π° Π»ΠΎΠ³Π° with open('test.log','rt',encoding='utf-8') as f: while True: line = f.readline() # Ρ‡ΠΈΡ‚Π°Π΅ΠΌ построчно if not line: break match = re.search(r_pattern, line) # Π˜Ρ‰Π΅ΠΌ if match: # И, найдя, подсчитываСм value = int(match.group(1)) + int(match.group(2)) print(value)