![](/img/trans.png)
[英]I need to extract data from multiple .txt files and move them to an Excel file, using Python
[英]Extract certain data from multiple .txt files using Python and RegEx
我有幾個.txt文件,我需要從中提取某些數據。 文件看起來很相似,但是每個文件存儲不同的數據。 這是該文件的示例:
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的豐富經驗,所以我不知道如何進一步發展。
這是我使用的代碼:
# 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()
您不需要正則表達式。 您可以使用基本的字符串函數:
txtfile=open(filename,"r")
for line in txtfile:
if line.startswidth("Start Date:"):
start_date = line.split()[-1]
...
如果您收集了所有信息,請break
。
要獲取Start Date
,可以使用以下正則表達式:
^(?: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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.