【发布时间】:2020-05-10 07:50:58
【问题描述】:
我正在尝试删除 .txt 文件中的某种文本模式,它看起来像:
mystring = '''
example deletion words
in the first block
First sentence to keep.
example deletion words
in the second block
Second sentence to keep.
example deletion words
in the third block
Third sentence to keep.
example deletion words
in the fourth block'''
我想要的输出如下所示:
“要保留的第一句话。
要保留的第二句话。
保留第三句。”
所以我要做的是去掉字符串“example”和“block”之间的所有文本,包括字符串本身。知道我将如何在 R 或 Python 中解决这个问题吗?
很抱歉忘记将我的正则表达式尝试包括在内,只是突然问,感谢那些不顾一切努力回答的人。我在 python 中使用 regex 和 re 包的工作解决方案:
import re
cleanedtext = re.sub('\nexample.*?block','',mystring, flags=re.DOTALL)
print(cleanedtext)
【问题讨论】:
-
On topic、how to ask 和 ...the perfect question 在这里申请。文件读/写和字符串操作的基本技术在许多教程中都有很好的记录;我们希望您做出合理的尝试在此处发帖。
-
@Prune 很抱歉留下这样的问题,我以为我会马上回来回答有关我的正则表达式尝试的问题,但我迷失了太久。不只是想留下空白问题,并且可以完全理解它的反对意见。
-
另见minimal, reproducible example。包括您得到的结果以及您的预期。
-
是的,我知道,再次,我真的很抱歉,我原本打算在发布问题后立即对其进行编辑,但我忘记了。不会再发生了。
-
既然您添加了一个可行的解决方案,我建议您不要使用它。我取消了我的关闭投票并将反对票改为赞成票。
标签: python r text-processing python-textprocessing