【问题标题】:Regular expression matching of the contents of text files in a directory目录中文本文件内容的正则表达式匹配
【发布时间】:2021-11-02 05:09:16
【问题描述】:

我有一个文本文件目录。我需要根据每个文件是否匹配 1、两个或都不匹配正则表达式模式为每个文件设置一个状态。我的计划是:

  1. 步行目录
  2. 如果文件的内容:
    • 不匹配任一模式,状态 = 1
    • 匹配模式 1 但不匹配模式 2,状态 = 2
    • 匹配 pattern2 但不匹配 pattern1,忽略
    • 匹配模式 1 和模式 2,状态 = 3
  3. 打印文件名和状态

我的代码:

pattern1 = re.compile(r'critical', re.IGNORECASE)
pattern2 = re.compile(r'gouting bile', re.IGNORECASE)

for file in os.listdir('/home/ea/medical'):
    if re.findall(pattern1, file) and re.findall(pattern2, file):
        status = 3
        print(file, "Status: ", status)
    elsif re.findall(pattern1, file) and not re.findall(pattern2, file):
        status = 2
        print(file, "Status: ", status)
    else:
        status = 1
        print(file, "Status: ", status)

我的问题是这不会返回任何东西。

【问题讨论】:

  • 如果它包含模式2但不包含模式1怎么办?
  • 您不需要使用findall()。你只需要知道是否至少有一个匹配,所以只需使用re.search()
  • @Barmar - 不是我们关心的情况。谢谢你的提问!
  • 是什么给了你这样的印象? re.findall() 的第二个参数是一个字符串,它返回在该字符串中找到的模式的所有匹配项。它怎么知道字符串是一个文件名,它应该读取文件?
  • 更不用说file 甚至不包含目录。所以即使它确实读取了文件,它也不知道在哪里找到它。

标签: python regex


【解决方案1】:

您需要读取文件,您只是根据文件名检查模式。

for file in os.listdir('/home/ea/medical'):
    contents = open(os.path.join('/home/ea/medical', file)).read()
    status = 1
    if re.search(pattern1, contents):
        status += 1
    if re.search(pattern2, contents):
        status += 1
    print(f"{file} Status: {status}")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多