简体   繁体   English

如果 python 的 txt 文件中存在,则从字符串中删除一个单词

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

Hey so I would like to remove a word from my string if this specific word is in my text file.嘿,如果这个特定的词在我的文本文件中,我想从我的字符串中删除一个词。 is this possible without storing my whole file in a list如果不将我的整个文件存储在列表中,这可能吗

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

I recommend you using string.replace(target,replacement) for this.我建议您为此使用 string.replace(target,replacement)。

First you need to read contents of.txt file that you have( like this ).首先,您需要阅读您拥有的 .txt 文件的内容( 像这样)。 I assume your txt looks something like this:我假设您的 txt 看起来像这样:

Word1,Word2,Word3,Word4字 1,字 2,字 3,字 4

Once you have converted.txt file content into an array you can do something like this:将.txt 文件内容转换为数组后,您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果包含来自python / bash中另一个.txt文件的单词,请从文件中删除行 - Remove line from file if containing word from another .txt file in python/bash 来自txt文件的Python字数统计程序 - Python word count program from txt file Python-从文本文件中删除单词或匹配字符串 - Python - remove a word or matching string from a text file 如何将 .txt 文件中的特定单词作为字符串变量导入 Python? - How do I import a specific word from a .txt file into Python as a string variable? 如何从.txt中删除一个单词 - How to remove a word from .txt 在python中导入txt文件,并在字符串中打印所有带有特定单词的行 - import a txt file in python and print all lines with specific word in string 使用正则表达式(python)从字符串中删除#{word} - Remove #{word} from a string using regex (python) 检查列表中的元素是否存在于 txt 文件的字符串中(不工作) Python - check if an element from a list exists in a strings of a txt file (not working) Python 在python中将字符串从txt文件转换为数组 - Converting a string from a txt file to an array in python 需要帮助从 .txt 文件中获取信息,但前提是输入的单词已经存在,使用 Python - Need help getting information out of a .txt file, but only if the entered word exists already, using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM