gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:15:30 24 4
gpt4 key购买 nike

我正在逐行读取文本文件,我想忽略所有出现的“and”、“To”和“From”并返回其余部分。 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 作为继续的一种方式。

关于python - 如何读取一行并忽略一些单词(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28220889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com