簡體   English   中英

如何從.txt中刪除一個單詞

[英]How to remove a word from .txt

我正在閱讀 file.txt,現在我想刪除重復的單詞。

c = collections.Counter()
with open('DatoSO.txt', 'rt') as f:
        for line in f:
            c.update(line.split())


for palabra,count in c.most_common():
   if count > 1 :
       with open('DatoSO.txt', 'rt') as f:
            Here REMOVE

我不知道如何從文件中刪除單詞

您不能從文件中刪除內容並將剩余內容向下移動。 您只能 append、截斷或覆蓋。

您最好的選擇是將文件讀入 memory,在 memory 中處理它,然后將其寫回磁盤。

使用正則表達式:

import re

...

f = re.sub(r'\w+\s?','',f)

不要使用重新

line.remove(string)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM