Skip to main content
 首页 » 编程设计

python之对文件夹中的多个文件运行数据解析器 Python

2024年10月24日11xxx_UU

长期潜伏,但从未在这里发布。抱歉,如果这不是一篇好文章...我制作了一个使用正则表达式从简历中提取姓名和电子邮件的程序。我可以让它打开我的简历文件夹中的特定文件,但是让程序遍历文件夹中的所有文件让我很困惑。这是我正在做的伪代码:

  • 打开简历文件夹
    • 读取文件1.txt
      • 执行名称查找器
      • 执行emailFinder
        • 创建新的字典candidateData
        • 导出到 Excel
    • 读取file2.txt
    • ...

代码如下:

import re 
import os 
import pprint 
 
with open('John Doe -Resume.txt', 'r') as f: 
 
    #This pulls the first line of the resume, 
    #Which is generally the name. 
    first_line_name = f.readline().strip() 
 
    #This pulls the Email from the resume. 
    bulkemails = f.read() 
    r = re.compile(r'(\b[\w.]+@+[\w.]+.+[\w.]\b)') 
    candidateEmail = r.findall(bulkemails) 
    emails = "" 
    for x in candidateEmail: 
            emails += str(x)+"\n" 
 
            #This creates the dictionary data 
            candidateData = {'candidateEmail' : str(candidateEmail), \ 
                              'candidateName' : str(first_line_name)} 
 
    pprint.pprint(candidateData) 

然后,我得到这个作为输出:

{'candidateEmail': "['JohnDoe@gmail.com']", 
'candidateName': 'John Doe'} 

一切准备就绪,可以导出到 Excel 中。

所以这是我要问你的问题!我如何让它对我的简历文件夹中的所有 .txt 文件执行此操作,而不仅仅是我指定的文件?另外,任何鳕鱼批评将不胜感激,谢谢大家!:D

请您参考如下方法:

您可以使用 glob 遍历目录中的所有 .txt 文件,然后对每个文件运行该函数。将此添加到开头

import re 
import os 
import glob 
import pprint 
 
os.chdir("resumes") 
for file in glob.glob("*.txt"): 
    with open(file, 'r') as f: 
        #Rest of your execution code here 

编辑:在评论中回答您的问题:

import re 
import os 
import glob 
import pprint 
 
candidateDataList = [] 
for file in glob.glob("*.txt"): 
    with open(file, 'r') as f: 
 
        #This pulls the first line of the resume, 
        #Which is generally the name. 
        first_line_name = f.readline().strip() 
 
        #This pulls the Email from the resume. 
        bulkemails = f.read() 
        r = re.compile(r'(\b[\w.]+@+[\w.]+.+[\w.]\b)') 
        candidateDataList.append({'name':str(first_line_name), 
                                  'email':r.findall(bulkemails)}) 
 
pprint.pprint(candidateDataList)