【问题标题】:Delete certain text pattern in python在python中删除某些文本模式
【发布时间】: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 topichow to ask 和 ...the perfect question 在这里申请。文件读/写和字符串操作的基本技术在许多教程中都有很好的记录;我们希望您做出合理的尝试在此处发帖。
  • @Prune 很抱歉留下这样的问题,我以为我会马上回来回答有关我的正则表达式尝试的问题,但我迷失了太久。不只是想留下空白问题,并且可以完全理解它的反对意见。
  • 另见minimal, reproducible example。包括您得到的结果以及您的预期。
  • 是的,我知道,再次,我真的很抱歉,我原本打算在发布问题后立即对其进行编辑,但我忘记了。不会再发生了。
  • 既然您添加了一个可行的解决方案,我建议您不要使用它。我取消了我的关闭投票并将反对票改为赞成票。

标签: python r text-processing python-textprocessing


【解决方案1】:

在 R 中,您可以使用来自 stringrstr_remove_all

stringr::str_remove_all(string, "example.*block")
 #[1] " First sentence to keep.\nSecond sentence to keep.\nThird sentence to keep.\n"

这是

的简写
stringr::str_replace_all(string, "example.*block", "")

数据

string <- "example deletion words in the first block First sentence to keep.
           example deletion words in the second blockSecond sentence to keep.
           example deletion words in the third blockThird sentence to keep.
           example deletion words in the fourth block"

【讨论】:

    【解决方案2】:

    您是否已经提前知道模式或者模式是否会改变?如果没有,那么您可以阅读文本文件,逐行查看,拆分句子以便轻松操作,然后查找模式。对于没有它的行,您可以将其连接到一个新字符串。我在下面的内容似乎有效:

    f = open("mytext.txt", "r")
    final = ""
    for line in f:
        words = line.split(" ")
        if(words[0] == "example" or words[len(words) - 1] == "block\n"):
            continue
        else:
            final = final + line
    print(final)
    

    我得到的输出是:

    First sentence to keep.
    
    
    Second sentence to keep.
    
    
    Third sentence to keep.
    

    【讨论】:

      猜你喜欢
      • 2016-03-03
      • 1970-01-01
      • 2015-06-22
      • 2023-03-23
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多