簡體   English   中英

每當pyspark中的一行出現任何錯誤詞時,我如何獲取文件中的下一行?

[英]How do i get the next lines in a file whenever any ERROR word come in a line in pyspark?

我有一個日志文件,我需要在其中檢查每一行。 每當“錯誤”字出現在任何一行時,我都需要在該行之后取下兩行。 我必須在 pyspark 中執行此操作。

例如:輸入日志文件:

1號線

2號線

行...錯誤... 3

4號線

5號線

6號線

輸出將是:

4號線

5號線

我已經使用日志文件創建了一個 rdd,並使用 map() 來遍歷每一行,但我沒有得到確切的想法。

提前致謝。

怎么樣:

# open your file as f
lines = f.readlines()
for i, line in enumerate(lines):
    if "ERROR" in line:
        print(lines[i+1])
        print(lines[i+2])
        # Exit or something you want to do.

這是使用窗口函數的方法:

from pyspark.sql import functions as F
from pyspark.sql.window import Window

# set up DF
df = sc.parallelize([["line1"], ["line2"], ["line3..ERROR"], ["line4"], ["line5"]]).toDF(['col'])

# create an indicator that created a boundary between consecutive errors
win1 = Window.orderBy('col')
df = df.withColumn('hit_error', F.expr("case when col like '%ERROR%' then 1 else 0 end"))
df = df.withColumn('cum_error', F.sum('hit_error').over(win1))

# now count the lines between each error occurrence
win2 = Window.partitionBy('cum_error').orderBy('col')
df = df.withColumn('rownum', F.row_number().over(win2))

# the lines we want are rows 2,3
df.filter("cum_error>0 and rownum in (2,3)").select("col").show(10)```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM