如何获得正则表达式匹配的整个行?

2024-09-25 08:38:50 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,在本书中,使用Python自动化无聊的内容,有一个家庭作业项目:

编写一个程序,该程序打开文件夹中的所有^{{cd1>}文件,并搜索与用户提供的正则表达式匹配的任何行。结果应该打印到屏幕上。

下面是我的代码。我有两个问题:

  1. 这个程序有较短的版本吗?
  2. 似乎regex行有问题(我希望regex与用户指定的regex出现的整行匹配),因为它没有显示lineReg下的任何结果。我试着删除regex的前导和尾部的括号。

import os, re

# Dir Location
print('Enter a directory location: (in which txt files are located)')
direct= input()
os.chdir(direct)

# Regexes
print("Enter the text you'd like to search for: (or a regex)")
givenReg= input()
soloReg= re.compile(givenReg)
lineReg= re.compile((r'^\n.*')+givenReg+(r'.*\n$'))
txtFileReg= re.compile(r'.*\.txt')

# Texts in Dir
txtFiles= os.listdir(direct)

# Finding line through Regex
for i in range(len(txtFiles)):
    if txtFileReg.search(txtFiles[i]) != None:
        file= open(txtFiles[i])
        read= file.read()

        outcomeSolo= soloReg.findall(read)
        outcomeLine= lineReg.findall(read)

        print('In ' + txtFiles[i] + ', found these matches:')
        print(outcomeLine)

        print('In ' + txtFiles[i] + ', the lines for these matches were:')
        print(outcomeSolo)

        print('\n')
        file.close()

Tags: 用户in程序reforreadosregex
1条回答
网友
1楼 · 发布于 2024-09-25 08:38:50

缩短程序的一种方法是使其行为更像一个典型的命令行程序:将输入作为参数,而不是通过某种类型的对话。在

另一种方法是减少输出的冗长。举一个例子看看grep是如何工作的。在

您还可以利用glob()。在

与其将整个文件读入内存,不如逐行遍历文件(这在类似的程序中有很多优点)。在

最后,我不清楚为什么要用自己的前导和尾随模式包装用户的正则表达式:让用户完全控制正则表达式(至少,我会这样做)。在

以下是这些要点的简短说明:

import sys, glob, re

dir_path = sys.argv[1]
rgx = re.compile(sys.argv[2])

for path in glob.glob(dir_path + '/*.txt'):
    with open(path) as fh:
        for line in fh:
            if rgx.search(line):
                msg = '{}:{}'.format(path, line)
                print(msg, end = '')

相关问题 更多 >