【问题标题】:how to fix the display format of the return result in python如何修复python中返回结果的显示格式
【发布时间】:2018-03-29 07:08:02
【问题描述】:

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

系统显示结果如下:

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        

【问题讨论】:

  • @Skandix 不基于用户输入。我想要的是显示结果的格式有待改进
  • 在循环中,存储各个行并增加一个计数器。在循环结束时,打印所有结果。

标签: python if-statement printing readfile


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 2015-11-21
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多