程式作業流程:
- 打開“asigra_backup.txt”檔案并讀取每一行
- 搜索確切的字串:“錯誤:” {任何值,范圍為 1 - 100}。例如“錯誤:12”
- 找到匹配項后,以 write&append 模式打開一個單獨的 .txt 檔案
- 寫下找到的匹配項。示例:“錯誤:4”
- 除了上述寫入之外,在步驟 3 中找到的匹配項下方附加接下來的 4 行;因為那是額外的日志資訊我做了什么:
- 在 regex101.com 上測驗了一個與我的示例資料匹配的正則運算式
- 使用串列理解在我的測驗檔案中查找所有匹配項我需要幫助的地方(請):
- 弄清楚如何在找到的每個匹配字串下方附加 4 行日志資訊
當前代碼:
result = [line.split("\n")[0] for line in open('asigra_backup.txt') if re.match('^Errors:\s([1-9]|[1-9][0-9]|100)',line)]
print(result)
當前輸出:
['Errors: 1', 'Errors: 128']
期望的輸出:
Errors: 1
Pasta
Fish
Dog
Doctonr
Errors: 128
Lemon
Seasoned
Rhinon
Goat
示例 .TXT 檔案
Errors: 1
Pasta
Fish
Dog
Doctonr
Errors: 128
Lemon
Seasoned
Rhinon
Goat
Errors: 0
Rhinon
Cat
Dog
Fish
uj5u.com熱心網友回復:
使用更好的正則運算式re.findall可以使它更容易。在以下正則運算式Errors: 中,檢測到所有和以下 4 行。
import re
regex_matches = re.findall('(?:[\r\n] |^)((Errors:\s*([1-9][0-9]?|100))(?:[\r\n\s\t] .*){4})', open('asigra_backup.txt', 'r').read())
open('separate.txt', 'a').write('\n' '\n'.join([i[0] for i in regex_matches]))
要訪問錯誤編號或錯誤行,可以使用以下行:
error_rows = [i[1] for i in regex_matches]
error_numbers = [i[2] for i in regex_matches]
print(error_rows)
print(error_numbers)
uj5u.com熱心網友回復:
我寫了一個代碼,它按要求列印輸出。Errors: 1將行添加為最后一行時,該代碼將起作用。查看我決議的文本:
data_to_parse = """
Errors: 56
Pasta
Fish
Dog
Doctonr
Errors: 0
Lemon
Seasoned
Rhinon
Goat
Errors: 45
Rhinon
Cat
Dog
Fish
Errors: 34
Rhinon
Cat
Dog
Fish1
Errors: 1
"""
請參閱不使用正則運算式即可提供所需輸出的代碼。索引已用于獲取所需的資料。
lines = data_to_parse.splitlines()
errors_indices = []
i = 0
k = 0
for line in lines: # where Errors: are located are found in saved in list errors_indices.
if 'Errors:' in line:
errors_indices.append(i)
i = i 1
#counter = False
while k < len(errors_indices):
counter = False # It is needed to find the indices when Errors: 0 is hit.
for j in range(errors_indices[k-1], errors_indices[k]):
if 'Errors:' in lines[j]:
lines2 = lines[j].split(':')
lines2_val = lines2[1].strip()
if int(lines2_val) != 0:
print(lines[j])
if int(lines2_val) == 0:
counter = True
elif 'Errors:' not in lines[j] and counter == False:
print(lines[j])
k=k 1
我已經嘗試了幾次以查看代碼是否正常作業。看起來它正確地給出了請求的輸出。查看代碼運行時的輸出:

uj5u.com熱心網友回復:
對于那些想要進一步澄清的人,因為它可能會幫助下一個人,這是我的最終解決方案:
def errors_to_file(self):
"""
Opens file containing Asigra backup logs, "asigra_backup.txt", and returns a list of all errors within the log.
Uses a regular expression match conditional on each line within the asigra backup log file. Error number range is 1 - 100.
Formats errors log by appending a space every 10th element in the errors log list.txt
Writes formatted error log to a file in current directory: "asigra_errors.txt"
"""
# "asigra_backup.txt" contains log information from the performed backup.
with open('asigra_backup.txt', "r") as f:
lines0 = [line.rstrip() for line in f]
# empty list that is appended with errors found in the log
lines = []
for i, line in enumerate(lines0):
if re.match('^Errors:\s([1-9]|[1-9][0-9]|100)',line):
lines.extend(lines0[i:i 9])
if len(lines) == 0:
print("No errors found")
print("Gracefully exiting")
sys.exit(1)
k = ''
N = 9
formatted_errors = list(chain(*[lines[i : i N] [k]
if len(lines[i : i N]) == N
else lines[i : i N]
for i in range(0, len(lines), N)]))
with open("asigra_errors.txt", "w") as e:
for i, line in enumerate(formatted_errors):
e.write(f"{line}\n")
非常感謝那些回答我問題的人。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465444.html
上一篇:如何從以下模型函式中洗掉回圈?
下一篇:將函式回傳的值寫入串列
