我在使用re.search的情况下实现了Grep:
#!/bin/python
"""
A grep implementation on Python
"""
from re import search
from sys import argv
def grep(word, file):
for line in file:
if search(word, line):
print(line.strip())
if __name__ == "__main__":
try:
grep(argv[1], open(argv[2]))
except FileNotFoundError:
print("That's not a vaild file.")
except IndexError:
print("Params missing!")但是,如果没有使用搜索I:
def grep(word, file):
for line in file:
if word in line:
print(line.strip())哪个更好,哪个更快?我认为第二种方式是毕达通的方式。
发布于 2021-08-24 04:48:09
您应该在第一个版本中使用re.escape(...)来匹配第二个版本的行为。没有它,word中的特殊字符可以解释为正则表达式模式。
捕获IndexError只会确保用户提供了足够的参数;它不会对太多的参数进行保护。如果存在,grep.py hello world file.txt将搜索world文件中的单词hello,而不是按预期搜索file.txt。检查实际的argv长度,或者更好地使用argparse模块。
发布于 2021-08-24 06:12:43
grep是一个命令行实用工具,用于搜索与正则表达式匹配的行的纯文本数据集。它的名称来自ed命令g/re/p (全局搜索正则表达式和打印匹配行)
因此,您的第二个grep实现实际上根本不是一个。取消资格案件结案。
https://codereview.stackexchange.com/questions/266336
复制相似问题