gpt4 book ai didi

python - 在多个文件中搜索多个正则表达式,然后输出每个匹配项及其各自的文件

转载 作者:太空宇宙 更新时间:2023-11-03 21:39:26 25 4
gpt4 key购买 nike

我正在尝试将输出格式化为表格。例如,所有匹配的文件应为列,而匹配实例应为行。

这是我的代码:

import glob
import re
folder_path = "/home/e136320"
file_pattern = "/*.txt"

match_list = []

folder_contents = glob.glob(folder_path + file_pattern)

#Search for Emails
regex1= re.compile(r'\S+@\S+')
#Search for Phone Numbers
regex2 = re.compile(r'\d\d\d[-]\d\d\d[-]\d\d\d\d')
#Search for Physician's Name
regex3=re.compile(r'\b\w\w\.\w+\b')


for file in folder_contents:
read_file = open(file, 'rt').read()
words=read_file.split()
for line in words:
email=regex1.findall(line)
phone=regex2.findall(line)
for word in email:
print(file,email)
for word in phone:
print(file,phone)

这是我的输出:

('/home/e136320/sample.txt', ['bcbs@aol.com'])
('/home/e136320/sample.txt', ['James@aol.com'])
('/home/e136320/sample.txt', ['248-981-3420'])
('/home/e136320/wow.txt', ['soccerfif@yahoo.com'])
('/home/e136320/wow.txt', ['313-806-6666'])
('/home/e136320/wow.txt', ['444-444-4444'])
('/home/e136320/wow.txt', ['248-805-6233'])
('/home/e136320/wow.txt', ['maliva@gmail.com'])

有什么想法吗?

最佳答案

我会尝试将您找到的项目附加到列表中,以便组织结果并在循环之间保留它们。然后你可以尝试打印出来。你可以尝试这样的事情:

import glob
import re

folder_path = "/home/e136320"
file_pattern = "/*.txt"

match_list = []

folder_contents = glob.glob(folder_path + file_pattern)

# Search for Emails
regex1= re.compile(r'\S+@\S+')

# Search for Phone Numbers
regex2 = re.compile(r'\d\d\d[-]\d\d\d[-]\d\d\d\d')

# Search for Physician's Name
regex3=re.compile(r'\b\w\w\.\w+\b')

results = {}

for file in folder_contents:
read_file = open(file, 'rt').read()
words=read_file.split()
current_results = []

for line in words:
email=regex1.findall(line)
phone=regex2.findall(line)

for word in email:
# Append email Regex matches to a list
current_results.append(word)

for word in phone:
# Append phone Regex matches to a list
current_results.append(word)

# Save results per file in a dictionary
# The file name is the key.
results[file] = current_results

for key in results.keys():
print(key, [str(item) for item in results[key]]

关于python - 在多个文件中搜索多个正则表达式,然后输出每个匹配项及其各自的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52995272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com