Home > Blockchain >  How do I count the number of strings in a text file only if that line contains another string?
How do I count the number of strings in a text file only if that line contains another string?

Time:09-23

I've created a python script that counts the total number of "302"s and "304"s in a text file. How would I get it to only count those strings in lines that also have "oct" as a string in that same line? Here's what I've attempted so far:

file = open('backup.txt','r')

codes = ["302", "304"]
total = 0
codesInOct = 0

lines = file.readlines()

for line in lines:
    if any(code in line for code in codes):
        total =1 
print('Total 3xx redirects: ', total)

for line in lines:
    if "oct" in line:
        if any(code in line for code in codes):
            codesInOct =1 
print('3xx redirects in october: ', codesInOct)

CodePudding user response:

Something like this?

file = 'backup.txt'

codes = ["302", "304"]
total = 0
codesInOct = 0

with open(file, 'r') as f:
    for line in f:
        if "oct" in line:
            for code in codes:
                if code in line:
                    total  = 1
                    codesInOct  = 1

print("Total: "   str(total))
print("Codes in oct: "   str(codesInOct))

CodePudding user response:

is it correct you want to get all 302 and 304 on Oct?

you can try this. (not tested)

file = open('backup.txt','r')

codes = ["302", "304"]
total = 0
codesInOct = 0

lines = file.readlines()

for line in lines:
    if (any(code in line for code in codes) and "oct" in line:
        total =1 
print('Total 3xx redirects in Oct: ', total)
  • Related