如何阅读一行并忽略一些单词 (python)

how to read a line and ignore some words (python)

我正在逐行读取文本文件,我想忽略所有出现的 "and" 、 "To" 和 "From" 以及 return 其余部分。 python 中是否有允许我这样做的功能?谢谢你的帮助。

要么使用替换,要么在空格处拆分行,并在没有您不需要的单词的情况下重新组合,例如:

In [6]: testsrt = 'I\'m reading a text file line by line and i want to ignore all occurrences of and , To and From and return the rest. Is there a function in python that will allow me to do that? Thanks for your help.'

In [7]: ts = testsrt.split(' ')                                                                                                                                                                                                                   

In [8]: excl = ["and", "To", "From"]                                                                                                                                                                                                              

In [9]: ' '.join([t for t in ts if not t in excl])                                                                                                                                                                                                
Out[9]: "I'm reading a text file line by line i want to ignore all occurrences of , return the rest. Is there a function in python that will allow me to do that? Thanks for your help."                                                          

请注意,如果您保留引号,则不会删除这些词,因为这是逐词工作的。

您也可以将 re.replace 视为一种处理方式。