首页 > 解决方案 > Python - 使用正则表达式从文本中提取代码

问题描述

我是一名 Python 初学者,正在寻求有关提取问题的帮助。

我有一堆文本文件,需要提取表达式的所有特殊组合(“C”+“正好 9 个数字”)并将它们写入一个包含文本文件文件名的文件。我想捕捉的表达式的每次出现都从新行的开头开始,并以“/n”结尾。

sample_text = """Some random text here 
and here
and here
C123456789
some random text here
C987654321
and here
and here"""

输出应该是什么样子(在输出文件中)

My_desired_output_file = "filename,C123456789,C987654321"

到目前为止我的代码:

min_file_size = 5

def list_textfiles(directory, min_file_size): # Creates a list of all files stored in DIRECTORY ending on '.txt'
    textfiles = []
    for root, dirs, files in os.walk(directory):
        for name in files:
            filename = os.path.join(root, name)
            if os.stat(filename).st_size > min_file_size:
                textfiles.append(filename)

for filename in list_textfiles(temp_directory, min_file_size):         
    string = str(filename)
    text = infile.read()
    regex = ???
    with open(filename, 'w', encoding="utf-8") as outfile:
       outfile.write(regex)

标签: pythonregextext-extraction

解决方案


你的正则表达式是'^C[0-9]{9}$'

^           start of line
C           exact match
[0-9]       any digit
{9}         9 times
$           end of line

推荐阅读