簡體   English   中英

僅當該行包含另一個字符串時,如何計算文本文件中的字符串數?

[英]How do I count the number of strings in a text file only if that line contains another string?

我創建了一個 python 腳本,用於計算文本文件中“302”和“304”的總數。 我怎樣才能讓它只計算那些在同一行中也有“oct”作為字符串的行中的字符串? 這是我到目前為止所嘗試的:

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)

像這樣的東西?

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))

您想在 10 月獲得所有 302 和 304 是否正確?

你可以試試這個。 (未測試)

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)

暫無
暫無

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

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