使用Python和RegEx从多个.txt文件中提取特定数据
我有几个.txt文件,我需要从中提取某些数据。文件看起来相似,但每个文件存储不同的数据。下面是该文件的一个示例:使用Python和RegEx从多个.txt文件中提取特定数据,python,regex,extract,Python,Regex,Extract,我有几个.txt文件,我需要从中提取某些数据。文件看起来相似,但每个文件存储不同的数据。下面是该文件的一个示例: Start Date: 21/05/2016 Format: TIFF Resolution: 300dpi Source: X Company ... 文本文件中有更多信息,但我需要提取开始日期、格式和分辨率。文件位于同一父目录(“E:\Images”)中,但每个文件都有自己的文件夹。因此,我需要一个脚本来递
Start Date: 21/05/2016
Format: TIFF
Resolution: 300dpi
Source: X Company
...
文本文件中有更多信息,但我需要提取开始日期、格式和分辨率。文件位于同一父目录(“E:\Images”)中,但每个文件都有自己的文件夹。因此,我需要一个脚本来递归读取这些文件。以下是我目前的脚本:
#importing a library
import os
#defining location of parent folder
BASE_DIRECTORY = 'E:\Images'
#scanning through subfolders
for dirpath, dirnames, filenames in os.walk(BASE_DIRECTORY):
for filename in filenames:
#defining file type
txtfile=open(filename,"r")
txtfile_full_path = os.path.join(dirpath, filename)
try:
for line in txtfile:
if line.startswidth('Start Date:'):
start_date = line.split()[-1]
elif line.startswidth('Format:'):
data_format = line.split()[-1]
elif line.startswidth('Resolution:'):
resolution = line.split()[-1]
print(
txtfile_full_path,
start_date,
data_format,
resolution)
理想情况下,如果Python将其与ech文件的名称一起提取并保存在文本文件中可能会更好。因为我在Python方面没有太多经验,我不知道如何进一步发展。您不需要正则表达式。你可以用 基本字符串函数:
txtfile=open(filename,"r")
for line in txtfile:
if line.startswidth("Start Date:"):
start_date = line.split()[-1]
...
break
如果收集了所有信息。要获取开始日期,可以使用以下正则表达式:
^(?:Start Date:)\D*(\d+/\d+/\d+)$
# ^ anchor the regex to the start of the line
# capture the string "Start Date:" in a group
# followed by non digits zero or unlimited times
# followed by a group with the start date in it
在Python
中,这将是:
import re
regex = r"^(?:Start Date:)\D*(\d+/\d+/\d+)$"
# the variable line points to your line in the file
if re.search(regex, line):
# do sth. useful here
请参阅a。以下是我使用的代码:
# importing libraries
import os
# defining location of parent folder
BASE_DIRECTORY = 'E:\Images'
output_file = open('output.txt', 'w')
output = {}
file_list = []
# scanning through sub folders
for (dirpath, dirnames, filenames) in os.walk(BASE_DIRECTORY):
for f in filenames:
if 'txt' in str(f):
e = os.path.join(str(dirpath), str(f))
file_list.append(e)
for f in file_list:
print f
txtfile = open(f, 'r')
output[f] = []
for line in txtfile:
if 'Start Date:' in line:
output[f].append(line)
elif 'Format' in line:
output[f].append(line)
elif 'Resolution' in line:
output[f].append(line)
tabs = []
for tab in output:
tabs.append(tab)
tabs.sort()
for tab in tabs:
output_file.write(tab + '\n')
output_file.write('\n')
for row in output[tab]:
output_file.write(row + '')
output_file.write('\n')
output_file.write('----------------------------------------------------------\n')
raw_input()
嗨,谢谢你的回答。问题是日期格式并不总是相同的(例如2003年9月22日至10月18日),因此我不能真正使用此代码。我在代码中使用了您的示例,但它仍然不起作用。我想我没有正确地插入它,但我希望python递归地读取父文件夹中的所有子文件夹,并一次提取所有信息。它还按字母顺序对文本文件排序。太棒了!我有类似的处理要做。例如,它也有地址字段,跨越多行。我应该如何显示它已经结束?