【问题标题】:Open and read all text Files in your directory and filter them using regular expression, python打开并读取目录中的所有文本文件并使用正则表达式 python 过滤它们
【发布时间】:2019-03-19 11:31:01
【问题描述】:

所以,我得到了一个用例。用例是一次使用正则表达式和 python 在多个文本文件中查找 PHI。

所以基本上,打开目录中的所有文本文件,然后使用正则表达式过滤每个文件的内容,以查看哪个文件中包含 PHI。

有什么想法吗?

【问题讨论】:

  • 你不需要正则表达式。使用os.listdir 获取您需要的目录中的所有文件。使用open方法打开它们,读取内容并使用if "PHI" in contents:过滤您需要的内容

标签: python regex nlp nltk


【解决方案1】:

这是使用glob 而不是listdir,但这可能是一种可能的方法。不过这里也不涉及正则表达式。

import glob

folder_path = "C:\Temp"
file_pattern = "\*.txt"
search_string = "hello"

match_list = []

folder_contents = glob.glob(folder_path + file_pattern)

for file in folder_contents:
    print("Checking", file)
    read_file = open(file, 'rt').read()

    if search_string in read_file:
        match_list.append(file)

print("Files containing search string")
for file in match_list:
    print(file)

【讨论】:

  • 非常感谢。效果很好。您知道如何在其中添加正则表达式过滤器吗?例如,如果我想搜索这个正则表达式,r'\d\d\d[-]\d\d\d[-]\d\d\d\d',我将如何实现呢?
猜你喜欢
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
  • 1970-01-01
相关资源
最近更新 更多