首页 > 解决方案 > 如果它存在于python的txt文件中,则从字符串中删除一个单词

问题描述

嘿,如果这个特定的词在我的文本文件中,我想从我的字符串中删除一个词。如果不将我的整个文件存储在列表中,这可能吗

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

标签: python

解决方案


我建议您为此使用 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

推荐阅读