相当于 GNU 'cat' 的 python 显示唯一行

标签 python

有没有人写过 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/

相关文章:

python - 在搁置中保存 lxml 元素时出现类型错误

python - 在Python中处理excel文件

python - 使用 python 从 s3 加载文件及其子文件夹

python - python中高效的在线线性回归算法

java - 通过 Excel 与 Python/Java/其他编程语言访问 Bloomberg 的 API

python - UnicodeEncodeError :'charmap' 与 'Ö' ,'Ç' 等

python - Python 中的简单 if 比较因 float 而失败

python - 如何在 Python 中获取项目的当前路径?

python - 从Python中的多行字符串解析消息

Python 异步套接字接收不工作