我安装了PythonXY。如何在IPython中使用或安装grep
或类似grep
的函数?它给出了grep
未定义的错误。我想在目录中的文本文件中搜索文本。
答案 0 :(得分:3)
只需使用python(> = 2.5)代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JQuery navigation test 2</title>
<script src="js/jquery-1.11.1.min.js" type="text/javascript"></script>
<style>
#nav {
float: left;
width: 280px;
border-top: 1px solid #999;
border-right: 1px solid #999;
border-left: 1px solid #999;
}
#nav li a {
display: block;
padding: 10px 15px;
background: #ccc;
border-top: 1px solid #eee;
border-bottom: 1px solid #999;
text-decoration: none;
color: #000;
}
#nav li a:hover, #nav li a.active {
background: #999;
color: #fff;
}
#nav li ul {
display: none;
}
#nav li ul li a {
padding: 10px 25px;
background: #ececec;
border-bottom: 1px dotted #ccc;
}
</style>
</head>
<body>
<ul id="nav">
<li><a href="#">Menu 1</a>
<ul>
<li><a href="#">Sub-Item 1 a</a></li>
<li><a href="#">Sub-Item 1 b</a></li>
<li><a href="#">Sub-Item 1 c</a></li>
</ul>
</li>
<li><a href="https://google.com">Link 1</a>
</li>
<li><a href="#">Menu 2</a>
<ul>
<li><a href="#">Sub-Item 3 a</a></li>
<li><a href="#">Sub-Item 3 b</a></li>
<li><a href="#">Sub-Item 3 c</a></li>
<li><a href="#">Sub-Item 3 d</a></li>
</ul>
</li>
<li><a href="#">Menu 3</a>
<ul>
<li><a href="#">Sub-Item 4 a</a></li>
<li><a href="#">Sub-Item 4 b</a></li>
<li><a href="#">Sub-Item 4 c</a></li>
</ul>
</li>
<li><a href="https://google.com">Link 2</a>
</li>
</ul>
<script type="text/javascript">
$(document).ready(function () {
$('#nav > li > a').click(function(){
if ($(this).attr('class') != 'active'){
$(this).next().slideToggle();
$(this).addClass('active');
}
else {
$(this).next().slideToggle();
$('#nav li a').removeClass('active');
}
});
});
</script>
</body>
</html>
然后你可以这样使用它:
import fileinput
import re
import glob
def grep(PAT, FILES):
for line in fileinput.input(glob.glob(FILES)):
if re.search(PAT, line):
print fileinput.filename(), fileinput.lineno(), line
答案 1 :(得分:2)
假设你在* nix系统上,你可以这样做:
文件: file_1.txt
this is line one
this is line two
this is line three
代码:
import os
import subprocess
os.system('grep one file_1.txt')
subprocess.call(['grep', 'one', 'file_1.txt'])
两种情况下的输出:
this is line one