我正在逐行阅读文本文件,我想忽略所有“and”,“To”和“From”的出现并返回其余部分。 python中有一个函数可以让我这样做吗?谢谢你的帮助。
答案 0 :(得分:3)
使用替换或拆分空格中的行并重新组合而不使用您不需要的单词,例如:
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
视为继续进行的方式。