如何修复 return 结果在 python 中的显示格式

how to fix the display format of the return result in python

我有一个函数可以读取文件并使用正则表达式显示匹配的词。

系统显示结果如下:

if
Exist on Line 1
if
Exist on Line 2

我想要的是让结果看起来像这样:

if exist 2 times
on line 1
on line 2

代码:

def searchWord(self,selectedFile):
        fileToSearchInside = self.readFile(selectedFile)
        searchedSTR = self.lineEditSearch.text()

        textList = fileToSearchInside.split('\n')

        counter = 1
        for myLine in textList:
            theMatch = re.findall(searchedSTR,myLine,re.MULTILINE|re.IGNORECASE)

            if(len(theMatch) > 0 ):
                print(theMatch[0])
                print("Exist on Line {0}".format(counter))
                counter+=1        

您可以保留一个字典,将关键字映射到它们的所有出现位置。

from collections import defaultdict
d = defaultdict(list)    # utility that gives an empty list for each key by default

for counter, myLine in enumerate(textList):
    matches = re.findall(searchedSTR, myLine, re.MULTILINE | re.IGNORECASE)
    if len(matches) > 0:
        d[matches[0]].append(counter + 1)  # add one record for the match (add one because line numbers start with 1)

for match, positions in d.items():   # print out
    print('{} exists {} times'.format(match, len(positions)))
    for p in positions:
        print("on line {}".format(p))

输出会像

if exists 2 times
on line 1
on line 2

正如我无法从描述中看出的那样,如果您的应用程序不搜索多个关键字,只需忘记 dict 并仅使用一个 list.