簡體   English   中英

Python中查找子串,獲取多個文件txt中的位置和出現次數

[英]Find substring, get the position and occurrence in multiple files txt in Python

編寫一個可以使用多個搜索關鍵字並從多個文件中搜索它們的 Python。 文件列表包含完全限定的路徑表達式,讀取文件的路徑可能不同。 以下是示例運行的輸出:

===============  file 1  ===============
Searching in C:\backTemp\amazonKDP\python\coding\ch5stProb1.text
'attack' appears 5 times at the position  32 64 396 956 1177
'and' appears 2 times at the position  539 897

===============  file 2  ===============
Searching in C:\backTemp\amazonKDP\python\coding\nine11.data
'attack' appears 2 times at the position  137 491
'and' appears 3 times at the position  113 363 559

他給出的提示是使用string.find ,但它只是使用字符串工作,所以我不知道如何解決這個問題並給出他想要的輸出。

我的代碼使用字符串而不是導入文件:

fInd = str.find(sch)


fInd = str.find(sch)
if fInd >= 0:
    sInd = str.find(sch, fInd +1)
    if sInd >= 0:
        print ("\"{}\" appears at the position".format (sch), fInd, sInd)
else:
    print ("not found")

這是我到目前為止得到的:

fileLst = [
    "path/filetxt",
    "path2/file2.txt",
]
searchLst = ["attack", "and"]


for i, file in enumerate(fileLst):
    print("="*15, "file {}".format(i+1), "="*15)
    print("Searching in {}".format(file))
    string = open(file).read()
    for sch in searchLst:
        indL = finding(string, sch, 0 , [])
        print ("'{}'appears {} times at the position".format(indL(string,sch,i+1)))
    for sch in searchLst:
        indL = finding(string,sch,1,[])
        print ("'{}'appears {} times at the position")

我必須修復正在返回的發現:

 indL = finding(string, sch, 0 , [])
TypeError: 'list' object is not callable

我很確定這行不通

print ("'{}'appears {} times at the position".format(indL(string,sch,i+1)))

暫無
暫無

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

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