因此,在本书中,使用Python自动化无聊的内容,有一个家庭作业项目:
编写一个程序,该程序打开文件夹中的所有^{{cd1>}文件,并搜索与用户提供的正则表达式匹配的任何行。结果应该打印到屏幕上。
下面是我的代码。我有两个问题:
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()
。在与其将整个文件读入内存,不如逐行遍历文件(这在类似的程序中有很多优点)。在
最后,我不清楚为什么要用自己的前导和尾随模式包装用户的正则表达式:让用户完全控制正则表达式(至少,我会这样做)。在
以下是这些要点的简短说明:
相关问题 更多 >
编程相关推荐