我有遍歷文件遞歸查找單詞從列表中的代碼。如果找到它,則會打印出找到的文件,搜索到的字符串以及找到的行。findall()正則表達式迭代通過文件從列表中尋找單詞
我的問題是,當搜索api
也匹配myapistring
,'通'匹配'指南針','dev'匹配'設備'而不是實際的單詞。所以我需要在某處實現一個正則表達式,但我不確定在for循環的哪個部分和哪個部分。
我已經得到了我(覺得)的正則表達式的工作原理是:
regex='([\w.]+)'
rootpath=myDir
wordlist=["api","pass","dev"]
exclude=["testfolder","testfolder2"]
complist=[]
for word in wordlist:
complist.extend([re.compile(word)])
for path,name,fname in os.walk(rootpath):
name[:] = [d for d in name if d not in exclude]
for fileNum in fname:
i=path+"/"+fileNum
files.append(i)
for fileLine in files:
if any(ext in fileLine for ext in exten):
count=0
for line in open(fileLine, "r").readlines():
count=count+1
for lv in complist:
match = lv.findall(line, re.IGNORECASE)
for mat in match:
[print output]
感謝
編輯: 加入提供了這個代碼:
for word in wordlist:
complist.extend([re.compile('\b' + re.escape(word) + '\b')])
與幾個工作錯誤,但足夠好,我可以與之合作。
的http://計算器。 com/questions/15863066/python-regular-expression-match-whole-word –
謝謝,但這並不能幫助我在哪裏放置正則表達式,以便它只找到整行中的單詞而不是一個實例字。 – Bob
我不知道python,但是我可以在這行之後猜測: 「for line in open(fileLine,」r「)。readlines():」with line as「re.search(r'\ bis \ b' ,線)「 –