python - 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)
解决方案
你的正则表达式是'^C[0-9]{9}$'
^ start of line
C exact match
[0-9] any digit
{9} 9 times
$ end of line
推荐阅读
- azure - 有没有办法在多个 pod 上启用托管身份?
- vue.js - 使用嵌套选项卡在 vuejs 中导航
- laravel - 使用 for 中生成的键和值创建关联数组
- php - PHP - 退出防止弹出
- amazon-web-services - 无法通过api网关调用rest api springboot lambda
- android - 在 PagerAdapter 中调用 API 后如何更新布局包含
- java - JAXB:两个 xsd 具有两个同名的复杂类型
- android - 如何在recyclerview上动态生成具有浅色填充颜色和相同颜色深阴影的可绘制色调的圆形可绘制对象
- arrays - Unity JSON 创建在数组上显示错误
- forms - symfony 搜索表单保持搜索参数