Py学习  »  Python

在Python中,并非所有副本都会从文本文件中删除

pinkkdeerr • 3 年前 • 1584 次点击  

我是Python新手。我正在尝试通过执行以下操作从文本文件中删除重复项:

line_seen = set()

f = open('a.txt', 'r')
w = open('out.txt', 'w')

for i in f:
    if i not in line_seen:
            w.write(i)
            line_seen.add(i)

f.close()
w.close()

在我最初的文件中

hello
world
python
world
hello

在我得到的输出文件中

hello
world
python
hello

因此,它没有删除最后一个副本。有谁能帮我理解为什么会发生这种事,我该如何解决它?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129280
 
1584 次点击  
文章 [ 4 ]  |  最新文章 3 年前
Leshawn Rice
Reply   •   1 楼
Leshawn Rice    3 年前
# Since we check if the line exists in lines, we can use a list instead of
# a set to preserve order
lines = []

infile = open('a.txt', 'r')
outfile = open('out.txt', 'w')

# Use the readlines method
for line in infile.readlines():
    if line not in lines:
        # Strip whitespace
        line = line.strip()
        lines.append(line)

for line in lines:
    # Add the whitespace back
    outfile.write("{}\n".format(line))

infile.close()
outfile.close()
gnight
Reply   •   2 楼
gnight    3 年前

很可能你没有用换行符结束最后一行。已知的行是“hello\n”。最后一句只是“你好”

修复输入或读取 i

Amirhossein Kiani
Reply   •   3 楼
Amirhossein Kiani    3 年前

主要问题是换行符(“\n”)出现在每行末尾,但最后一行除外。你可以结合使用 set , map join 功能如下:

f = open('a.txt', 'r')
w = open('out.txt', 'w')
w.write("\n".join(list(set(map(str.strip,f.readlines())))))

出来txt

python
world
hello

如果你想坚持以前的方法,你可以使用:

line_seen = set()

f = open('a.txt', 'r')
w = open('out.txt', 'w')

for i in f:
  i = i.strip()
  if i not in line_seen:
    w.write(i)
    line_seen.add(i)

f.close()
w.close()
Patrick Artner
Reply   •   4 楼
Patrick Artner    3 年前

第一行可能包含 'hello\n' -最后一行只包含 'hello' -它们不一样。

使用

line_seen = set()

with  open('a.txt', 'r') as f, open('out.txt', 'w') as w:

    for i in f:
        i = i.strip()            # remove the \n from line
        if i not in line_seen:
            w.write(i + "\n")
            line_seen.add(i)