Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

When a certain word is repeated in lines, print something in Python

  1. Whenever the word "Run" comes in line, then print "Vader".
  2. If the word "Alert" repeats consecutively before "Run", then print "skip" equal to the number of times it repeats.

Sample input

Alert and be on guard

Run for your life

Alert and be on guard

Alert and be on guard

Run for your life

Alert and be on guard

Alert and be on guard

Alert and be on guard

Run for your life

Alert and be on guard

Alert and be on guard

Run for your life

My code so far

sys.stdout = open("filepath/output.csv", "w")
with open("filepath/input.txt", "r") as f:
            for line in f:
                if "Run" in line:
                    print("Vader")

sys.stdout.close() 

current output

Vader

Vader

Vader

Vader

Required output

Vader

skip

Vader

skip

skip

Vader

skip

Vader

As you can see, I have completed the first requirement. Can't figure out the second part. Can someone help with point#2? Or point me in the right direction? Thanks.

question from:https://stackoverflow.com/questions/65944005/when-a-certain-word-is-repeated-in-lines-print-something-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Iterate over the lines, and whenever there is "Alert", increment a counter. If the counter is > 1, print "skip". When Alert is not present, reset counter to 0.

counter = 0
for line in f:
    if "Run" in line:
        print("Vader")
        counter = 0
    elif "Alert" in line:
        if counter > 1:
            prit("skip")
        counter += 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...