我有一些記錄輸入名稱和分數的代碼,我想讓它只能有 3 個同名條目,因此我試圖弄清楚如何檢查檔案中的某個字串并確保存在只是那個字串中的 3 個。這是我之前找到的代碼,但我想這樣做,一旦它識別出 3 個名稱(如果有 3 個名稱),就會終止程式。
# checks for multiple name entries max 3
def maxNamesA1():
count = 0
with open('testResultA1.txt') as myfile:
if name in myfile.read():
count = 1
print(count)
uj5u.com熱心網友回復:
您需要遍歷各行以獲取計數,截至目前,您只會增加任何匹配項的帳戶。
# checks for multiple name entries max 3
def maxNamesA1():
count = 0
with open('testResultA1.txt') as myfile:
count = sum([1 for line in myfile if name in line])
# to terminate
if count > 3: exit()
return count
uj5u.com熱心網友回復:
使用`str.count:
with open('testResultA1.txt') as myfile:
print(myfile.read().count(name))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343742.html
標籤:Python
上一篇:提取檔案中兩個句子之間的行
