所以在《用 Python 自动完成无聊的事情》一书中,有这样一个家庭作业项目:
编写一个程序,打开文件夹中的所有 .txt
文件,并搜索与用户提供的正则表达式匹配的任何行。结果应打印到屏幕上。
下面是我的代码。我有两个问题:
- 该程序有较短的版本吗?
- 行正则表达式似乎有问题(我想要一个正则表达式来匹配用户指定的正则表达式出现的整行),因为它没有在 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/