Vin*_*jip 61
在Unix/Linux上,uniq按照David Locke的回答使用命令,或者sort根据William Pursell的评论.
如果您需要Python脚本:
lines_seen = set() # holds lines already seen
outfile = open(outfilename, "w")
for line in open(infilename, "r"):
if line not in lines_seen: # not a duplicate
outfile.write(line)
lines_seen.add(line)
outfile.close()
Run Code Online (Sandbox Code Playgroud)
更新:本sort/ uniq组合将删除重复,但返回与排序线,这可能会或可能不是你想要的是一个文件.上面的Python脚本不会重新排序行,但只删除重复项.当然,为了让上面的脚本也进行排序,只需outfile.write(line)在循环之后立即省略,而不是outfile.writelines(sorted(lines_seen)).
Dav*_*cke 35
如果您使用的是*nix,请尝试运行以下命令:
sort <file name> | uniq
Run Code Online (Sandbox Code Playgroud)
mar*_*ell 16
uniqlines = set(open('/tmp/foo').readlines())
Run Code Online (Sandbox Code Playgroud)
这将为您提供唯一线条列表.
将其写回某个文件就像下面这样简单:
bar = open('/tmp/bar', 'w').writelines(set(uniqlines))
bar.close()
Run Code Online (Sandbox Code Playgroud)
你可以做:
import os
os.system("awk '!x[$0]++' /path/to/file > /path/to/rem-dups")
Run Code Online (Sandbox Code Playgroud)
在这里,您正在使用bash到python :)
您还有其他方法:
with open('/tmp/result.txt') as result:
uniqlines = set(result.readlines())
with open('/tmp/rmdup.txt', 'w') as rmdup:
rmdup.writelines(set(uniqlines))
Run Code Online (Sandbox Code Playgroud)
它的重点已经在这里说过了 - 我在这里使用的是什么.
import optparse
def removeDups(inputfile, outputfile):
lines=open(inputfile, 'r').readlines()
lines_set = set(lines)
out=open(outputfile, 'w')
for line in lines_set:
out.write(line)
def main():
parser = optparse.OptionParser('usage %prog ' +\
'-i <inputfile> -o <outputfile>')
parser.add_option('-i', dest='inputfile', type='string',
help='specify your input file')
parser.add_option('-o', dest='outputfile', type='string',
help='specify your output file')
(options, args) = parser.parse_args()
inputfile = options.inputfile
outputfile = options.outputfile
if (inputfile == None) or (outputfile == None):
print parser.usage
exit(1)
else:
removeDups(inputfile, outputfile)
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
获取列表中的所有行并制作一组行,您就完成了。例如,
>>> x = ["line1","line2","line3","line2","line1"]
>>> list(set(x))
['line3', 'line2', 'line1']
>>>
Run Code Online (Sandbox Code Playgroud)
如果您需要保留行的顺序 - 因为 set 是无序集合 - 试试这个:
y = []
for l in x:
if l not in y:
y.append(l)
Run Code Online (Sandbox Code Playgroud)
并将内容写回文件。
| 归档时间: |
|
| 查看次数: |
73937 次 |
| 最近记录: |