簡體   English   中英

如果 python 的 txt 文件中存在,則從字符串中刪除一個單詞

[英]remove a word from string if it exists in txt file in python

嘿,如果這個特定的詞在我的文本文件中,我想從我的字符串中刪除一個詞。 如果不將我的整個文件存儲在列表中,這可能嗎

removable_words # in this case is a txt file 
text = [w for w in text.split() if w not in removable_words]

我建議您為此使用 string.replace(target,replacement)。

首先,您需要閱讀您擁有的 .txt 文件的內容( 像這樣)。 我假設您的 txt 看起來像這樣:

字 1,字 2,字 3,字 4

將.txt 文件內容轉換為數組后,您可以執行以下操作:

for word in removable_words:
  text.replace(word,"") // This will replace word with empty string

暫無
暫無

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

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