有没有人写过 GNU cat python 中的命令并愿意分享? GNU cat 实际上做了很多,我今天真的不想重新发明轮子。是的,我确实进行了谷歌搜索,然后阅读了too many sad stories of kittens vs snakes我决定尝试 SO。
编辑:我想对其进行修改,使其只显示唯一的行。
最佳答案
最新: 感谢 Ned 提供的文件输入提示!这是最新的:
#!/usr/bin/python
"""cat the file, but only the unique lines
"""
import fileinput
if __name__ == "__main__":
lines=set()
for line in fileinput.input():
if not line in lines:
print line,
lines.add(line)
之前(2010-02-09):
这是我最终得到的结果。它可以满足我的迫切需要。感谢 Mike Graham 的帮助。
#!/usr/bin/python
"""cat the file, but only the unique lines
"""
import optparse
import sys
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.set_usage('%prog [OPTIONS]')
parser.set_description('cat a file, only unique lines')
(options,args) = parser.parse_args()
lines = set()
for file in args:
if file == "-":
f = sys.stdin
else:
f = open(file)
for line in f:
if not line in lines:
print line,
lines.add(line)
关于相当于 GNU 'cat' 的 python 显示唯一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2224554/