在第一个正则表达式行匹配中保留第二个正则表达式行

Keep second regex lines in first regex lines matches

提问人:Pubg Mobile 提问时间:11/12/2023 最后编辑:Pubg Mobile 更新时间:11/12/2023 访问量:64

问:

我的目录中有大量的txt列表文件,以下是我的一个文件的示例:E:\Desktop\Linux_distro\asliiiii

95
ROSA
139
96
Chakra
137
97
AV Linux
135
98
LibreELEC
134
99
Simplicity
131
100
Kodachi
130
20200301020449
79776361952441

现在我需要一个脚本,该脚本首先找到正则表达式行,然后在找到的行中仅保留正则表达式行。
这意味着必须向我提供以下结果:
\d{14}20(?:0[0-9]|1[0-9]|20)[0-1][0-9]

95
ROSA
139
96
Chakra
137
97
AV Linux
135
98
LibreELEC
134
99
Simplicity
131
100
Kodachi
130
20200301020449

我写了以下python脚本,但我不知道为什么它不适合我的列表!

import os
import re

def process_file(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()

    # Find lines matching \d{14}
    regex_pattern_1 = re.compile(r'\d{14}')
    matching_lines = [line.strip() for line in lines if regex_pattern_1.search(line)]

    # Keep only matches of the second regex in the found lines
    regex_pattern_2 = re.compile(r'20(?:0[0-9]|1[0-9]|20)[0-1][0-9]\d{8}')
    filtered_lines = []
    for line in matching_lines:
        matches = regex_pattern_2.findall(line)
        filtered_lines.extend(matches)

    # Write the filtered lines back to the file
    with open(file_path, 'w') as file:
        file.write('\n'.join(filtered_lines))

def process_files_in_directory(directory_path):
    for filename in os.listdir(directory_path):
        if filename.endswith('.txt'):
            file_path = os.path.join(directory_path, filename)
            process_file(file_path)

if __name__ == "__main__":
    directory_path = r'E:\Desktop\Linux_distro\asliiiii'
    process_files_in_directory(directory_path)
    print("Processing complete.")

但是这个脚本为我提供了以下结果!

20200301020449

这个脚本问题在哪里?

Python 正则表达式

评论

0赞 Tim Roberts 11/12/2023
这并不是一个真正的正则表达式问题。您需要一个循环来复制所有行,直到它达到一个 14 位数字的长度。然后,您进入另一个循环,该循环仅复制看起来像时间戳的行。
0赞 Pubg Mobile 11/12/2023
@TimRoberts tnq 但我非常乞求,请用代码和脚本解释。
0赞 Tim Roberts 11/12/2023
这不是免费的编码服务。您应该能够使用该描述拍摄自己的照片。
0赞 Pubg Mobile 11/12/2023
@TimRoberts我没有要求免费代码!我在后期提供了我的脚本!只需要回答我的脚本问题
0赞 Timeless 11/12/2023
你能使你的示例最小化和有意义并更新预期的输出吗?

答:

0赞 Reilas 11/12/2023 #1

请尝试以下操作。

matches = regex_pattern_2.findall(line[:6])

或者,调整模式以合并剩余的 8 个字符

20(?:0[0-9]|1[0-9]|20)[0-1][0-9]\d{8}

评论

0赞 Pubg Mobile 11/12/2023
TNQ 但我的脚本只保留20200301020449行并删除此帖子示例中的所有其他行,我不知道脚本问题在哪里!
0赞 Tim Roberts 11/12/2023 #2

这就是我的意思。太多人使用正则表达式来解决实际上并不需要它们的问题。

def process_file(fn):
    fin = open(fn)
    fout = open(fn+'.out','w')

    for line in fin:
        line = line.strip()
        print(line, file=fout)
        if len(line) == 14 and line.isdigit():
            break

    for line in fin:
        line = line.strip()
        if len(line) == 14 and line.isdigit() and line.startswith('20'):
            print(line, file=out)

process_file('x.txt')

现在,我做了一个假设,检查“以'20'开头的 14 位数字”足以找到您的时间戳,但如果您真的需要查找有效日期,您可以在此处使用正则表达式。

请注意,我复制到具有特殊名称的新文件中。如果你愿意,你可以做一个和最后。deleterename

评论

0赞 Pubg Mobile 11/12/2023
tnq 先生,我编辑了帖子并告诉问题是什么。请再次阅读我的帖子末尾。
0赞 Tim Roberts 11/12/2023
看看你的第一个循环,产生.该循环将仅包含与您的第一个模式匹配的行,有 14 位数字。然后,循环遍历这些行。你永远不会得到其他任何东西。你的方法是错误的。matching_lines
0赞 Pubg Mobile 11/12/2023 #3

以下脚本对我有好处:

import os
import re

def process_file(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()

    # Keep lines that match the second regex or do not match any regex
    regex_pattern_2 = re.compile(r'20(?:0[0-9]|1[0-9]|20)[0-1][0-9]\d{8}')
    filtered_lines = [line.strip() for line in lines if regex_pattern_2.search(line) or not re.search(r'\d{14}', line)]

    # Write the filtered lines back to the file
    with open(file_path, 'w') as file:
        file.write('\n'.join(filtered_lines))

def process_files_in_directory(directory_path):
    for filename in os.listdir(directory_path):
        if filename.endswith('.txt'):
            file_path = os.path.join(directory_path, filename)
            process_file(file_path)

if __name__ == "__main__":
    directory_path = r'E:\Desktop\Linux_distro\asliiiii'
    process_files_in_directory(directory_path)
    print("Processing complete.")