Python 用单个字符串替换文件中的重复字符串

Python 用单个字符串替换文件中的重复字符串,python,Python,我有一个文本文件,其行如下: "aa aa bb aa" "cc cc dd bb bb" 想要删除重复出现的令牌以获得这样的文件: "aa bb" "cc dd bb" 在python中: s = "aa aa bb aa" ' '.join(set(s.split())) 输出: 'aa bb' 如果订单很重要,请尝试以下方法: lst = [] [lst.append(i) for i in s.split() if i not in lst] ' '.join(lst) 大概是

我有一个文本文件,其行如下:

"aa aa bb aa"
"cc cc dd bb bb"
想要删除重复出现的令牌以获得这样的文件:

"aa bb"
"cc dd bb"
在python中:

s = "aa aa bb aa"
' '.join(set(s.split()))
输出:

'aa bb'
如果订单很重要,请尝试以下方法:

lst = []
[lst.append(i) for i in s.split() if i not in lst]
' '.join(lst)
大概是这样的:

from sets import Set
lines = ['aa aa bb aa','cc cc dd bb bb']
for l in lines:
    s = Set()
    for word in l.split():
        s.add(word)
    print ' '.join(s)
在Python2.7中 在Python3.x中
在这里。虽然这有点复杂,但它将维持秩序

>>> for e in s.split():
        c = set(e)
        for i in c:
            print(i)        
a
a
b
a
将其放在您的文件上下文中:

with open('datafile') as fin, open('outfile') as fout:
    for e in s.split():
        c = set(e)
        for i in c:
            print(i, end=' ' outfile=fout)
                    #print >> fout, i #Python 2.x

欢迎来到堆栈溢出!如果你想维持秩序,请花一分钟阅读接受的答案可能不起作用。我试过了,你是对的。但顺序对我来说并不重要,答案满足了问题的需要。我添加了一个保持顺序的答案,以防万一:)不推荐使用
set
模块。它已被一个更好的实现所取代,因为
set
frozenset
内置类型。您能举个例子吗?
set
将不会维持顺序。尝试在3.x中输入
“bb aa aa”
,您可以让
print
函数为您插入空格:
print(*(set(line.split()),file=fout)
@KarlKnechtel,好主意。我会使用它,这不保证维持订单。试试
s=“bb aa”
@thefourtheye看到订单的更新我相信它仍然是错误的。它只找到唯一的元素。最好不要在使用理解时产生副作用。
>>> for e in s.split():
        c = set(e)
        for i in c:
            print(i)        
a
a
b
a
with open('datafile') as fin, open('outfile') as fout:
    for e in s.split():
        c = set(e)
        for i in c:
            print(i, end=' ' outfile=fout)
                    #print >> fout, i #Python 2.x