![](/img/trans.png)
[英]Python: Remove substrings with fixed start and end from .txt file
[英]how to remove lines with duplicated substrings from txt file in python?
我正在嘗試從包含重復子字符串的 .txt 文件中刪除行。 假設我有這樣的行:
aaaaaa, something....
bbbbbb, something differet..
cccccc, some other text..
cccccc, again different text..
dddddd, again some other text..
eeeeee, some other text...
etc..
我想過濾掉以相同子字符串(前 N 個字符)開頭的所有行,以便只有一個(第一個)行以它開頭。 這些我想復制到一個新的txt文件。
所以在上面的例子中,前三行將被復制,第四行將被跳過,其余的將被復制。
我想復制所有行,而不僅僅是我正在檢查的子字符串
這是我根據我的發現寫的
lines_seen = set()
outfile = open(outfile, "w")
for line in open(infile, "r"):
string_to_compare = line[0:N] #save the substring into a variable
if line.startswith(string_to_compare) not in lines_seen:
outfile.write(line)
lines_seen.add(line)
outfile.close()
上面的這段代碼實際上將 outfile 中的所有行復制到 infile 中,因此沒有進行過濾。
誰能告訴我錯誤在哪里或如何使它起作用?
如果只對前 60 個字符感興趣,你應該只在你的集合中存儲這個切片( lines_see.add(string_to_compare)
)並且你的檢查應該更改為if string_to_compare not in lines_seen:
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.