如何使用python删除重复的文本块

时间:2018-10-25 15:57:03

标签: python regex nltk

我正在使用作为放射学报告的文本文件。如果一个文档有两个页面,则在所有页面的顶部都会重复一个包含患者姓名和其他元数据的文本块,而页面的其余部分则包含报告的内容。我已将页面合并为一个文本对象。保留第一个块,我想删除所有其他重复的块。有没有办法以编程方式从所有此类文件中删除这些块? 重复的块看起来像这样:

 Patient ID            xxx                 Patient Name           xxx
 Gender                 Female                         Age                     43Y 8M
 Procedure Name         CT Scan - Brain (Repeat)       Performed Date          14-03-2018
 Study DateTime         14-03-2018 07:10 am            Study Description       BRAIN REPEAT
 Study Type             CT                             Referring Physician     xxx

3 个答案:

答案 0 :(得分:0)

纯文本文件可以在python中表示为序列。考虑下面的plain.txt

This is the first line!\n
This is the second line!\n
This is the third line!\n

您可以使用with保留字来创建用于管理打开/关闭逻辑的上下文,如下所示:

with open("./plain.txt", "r") as file:
    for line in file:
        # program logic
        pass

"r"是指开放使用的模式。

因此,使用此惯用语,您可以存储重复值,并在遇到重复值时将其忽略,以适合您文件访问模式的方式进行。

编辑:我看到了您的编辑,看起来实际上是一个csv,对吗?如果是这样,我推荐熊猫包装。

import pandas as pd # Conventional namespace is pd

# Check out blob, os.walk, os.path for programmatic ways to generate this array
files = ["file.csv", "names.csv", "here.csv"] 

df = pd.DataFrame()
for filepath in files:
    df = df.append(pd.read_csv(filepath))

# To display result
print(df)

# To save to new csv
df.to_csv("big.csv")

答案 1 :(得分:0)

假设您可以将每个页面放入文档列表中

def remove_patient_data(documents: list, pattern: str) -> str:
    document_buffer = ""
    for count, document in enumerate(documents):
        if count != 0:
            document = document.replace(pattern, "")
        document_buffer += document + '\n'
    return document_buffer

my_documents = ["blah foo blah", "blah foo bar", "blah foo baz"]
remove_patient_data(my_documents, "foo")

哪个会回来

'blah foo blah\nblah bar\nblah baz\n'

答案 2 :(得分:0)

您可以通过以下操作找到所有出现的患者数据的起始索引:

str.find(sub,start,end)

其中

sub:需要在给定字符串中搜索的子字符串-在您的情况下,这将是患者数据 start:需要在字符串中检查sub的起始位置 end:需要在字符串

中检查后缀的结束位置

它将返回搜索到的字符串(患者数据)出现的最低索引。

您可以循环执行此过程,以获取发生患者数据的所有索引。

然后,您可以通过执行以下操作从第二个实例开始替换患者数据:

str_new = ''.join(( str_old[ : indicies[1] ], '' , s_old[ indicies[2] + len(str_old) + 1 : ] ))
  ... assuming a total of 3 pages in your record.

其他选择:

str.replace(old, new [, max])

其中

old:−这是要替换的旧子字符串-在您的情况下为患者数据
新增:−这是新的子字符串,它将替换旧的子字符串-这可以是''(空格) max:-如果给出此可选参数max,则仅替换第一个计数出现-这意味着患者数据现在仅出现在 last 页面上。