我正在尝试将输出格式化为表格。例如,所有匹配的文件都应作为列,而matchs实例应是行。
这是我的代码:
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'])
有什么想法吗?
答案 0 :(得分:0)
我会尝试将找到的项目追加到列表中,以便组织结果并在循环之间保持它们。然后,您可以尝试将其打印出来。您可以尝试这样的事情:
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]]