繁体   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