python - 如何获取正则表达式匹配的整行?

标签 python regex

所以在《用 Python 自动完成无聊的事情》一书中,有这样一个家庭作业项目:

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

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

  1. 该程序有较短的版本吗?
  2. 行正则表达式似乎有问题(我想要一个正则表达式来匹配用户指定的正则表达式出现的整行),因为它没有在 lineReg 下显示任何结果。我尝试删除正则表达式前导部分和尾随部分周围的括号。

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()

最佳答案

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

另一种方法是让输出不那么啰嗦。通过一个示例来了解 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 = '')

关于python - 如何获取正则表达式匹配的整行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48002016/

相关文章:

regex - 仅当表达式在 apache Camel 选择中起作用时才第一次?

regex - 搜索连续的序列违规

python - Pandas - 将 CSV 读入数据框,其中一列具有不同数量的子列

python - 我很困惑我们是否可以通过在代码中不提及元素索引来访问列表的内容。有人可以解释一下吗?

python - PyCharm 自动完成

python - 带有额外信息的 Django 表单

java - 使用正则表达式获取字符串的首字母,同时保留标点符号和空格

python - Django自定义管理命令运行Scrapy : How to include Scrapy's options?

正则表达式从文件中提取多行

regex - 使用正则表达式捕获单个表情符号