我正在搜索一個文本檔案,它是一個“電話簿”以進行分配,并且正在使用正則運算式 finditer,但是如果一個名稱中包含字母 a 兩次,它會將該行列印兩次,這是我試圖避免的。還有沒有辦法讓它忽略大小寫?
def searchPhonebook(s): #This will search the phonebook(s) for the inputed data that is assigned to d
print()
d=input("Please enter the Name, Character, Phone Number, or a number: ") #Variable d which is the inputted data
print()
import re
pattern = re.compile(d)
for line in open("phone.txt"):
for match in re.finditer(pattern,line):
print(line)
所以當我搜索“a”時它會回傳
Jack Hammer,277-4829
Jack Hammer,277-4829
Mike Rafone,345-3453
Earl Lee Riser,701-304-8293
所以我希望它每一個都回傳一次,并找到'a'的大寫,就像Abby
uj5u.com熱心網友回復:
不要使用findall(). 只需測驗該行是否與模式匹配:
for line in open("phone.txt"):
if re.search(pattern, line):
print(line)
實際上,我完全不知道您為什么要使用它re。您的用戶真的輸入了正則運算式模式嗎?如果他們只是輸入一個普通字串,請使用if d in line:
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377044.html
上一篇:未捕獲的型別錯誤:無法讀取未定義的屬性(讀取“使用”)
下一篇:串列串列中的普通串列
