需要对它们保存在txt文件中的顺序排序,只需要从下面输入新行并删除相似的单词后保存此顺序。所以,如果我逐个在循环中添加单词
line A
line B
line C
line D
line E
这里我有三个解决方案,但没有什么对我有用
首先只保留唯一的字词;
with open('C:\my_path\doc.txt', 'r') as lines:
lines_set = {line.strip() for line in lines}
with open(''D:\path\file.txt', 'w') as out:
for line in lines_set:
out.write(line + '\n')
但是破坏了秩序:
1. line B
2. line E
3. line C
4. line D
5. line A
第二个保持秩序,但同样的话:
with open('C:\my_path\doc.txt', 'r') as lines:
lines_set = []
for line in lines:
if line.strip() not in lines_set:
lines_set.append(line.strip())
最后一个效果很好,但输入文字:
with open('C:\my_path\doc.txt', 'r') as lines:
lines_set = []
for line in lines:
if line.strip() not in lines_set:
lines_set.append(line.strip())
在某些情况下我没有任何输入,也有不同的输入,所以需要以某种方式排序有序列表本身
你可以帮我解决一下吗
答案 0 :(得分:0)
loadLines
几乎与您展示两次的功能一样,但它允许重复。 removeDuplicates
删除重复项。 saveLines
将列表写入文件,通过换行符进行删除。所有功能都保留了订单。
#Load lines with duplicates
def loadLines(f):
with open(f, 'r') as lines:
lines_set = []
for line in lines:
lines_set.append(line.strip())
return lines_set
#Search list "l", return list without duplicates.
def removeDuplicates(l):
out = list(set(l))
for i in enumerate(out):
out[i[0]] = l.index(i[1])
out.sort()
for i in enumerate(out):
out[i[0]] = l[i[1]]
return out
#Write the lines "l" to filepath "f"
def saveLines(f, l):
open(f, 'w').write('\n'.join(l))
lines = loadLines('doc.txt')
print(lines)
stripped_lines = removeDuplicates(lines)
print(stripped_lines)
saveLines('doc.txt', stripped_lines)