Python实践练习:正则表达式查找

题目

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

代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 编写一个程序,打开文件夹中所有的.txt文件,查找匹配用户提供的正则表达式的所有行。结果应该打印到屏幕上

import re
import os
import sys

cwd = os.getcwd()
txtDirList = []

# 查找匹配的文件,并存入列表
regex1 = re.compile(r'.txt$')
for x in os.listdir(cwd):
    if regex1.search(x):
        txtDirList.append(x)
print(txtDirList)

# 根据传入的参数来匹配需要行
print(sys.argv[1])
regex2 = re.compile(sys.argv[1])
txtLineList = []
for x in txtDirList:
    with open(x, 'r', encoding='UTF-8') as txtFile:
        txtLineList = txtFile.readlines()
        for y in txtLineList:
            if regex2.search(y):
                print(y + '
')
原文地址:https://www.cnblogs.com/wudongwei/p/9016994.html