[英]Rearranging sections of lines of a file using regular expressions python
因此,我正在創建一個腳本,該腳本將通過具有特定格式的文件,並將其重新排列為與另一個文件相同的格式。 這是未格式化文件的示例
, 0x40a846, mov [ecx+2bh],al, 88 41 2B, , , , \par
, 0x40a849, jmp $+001775cbh (0x581e14), E9 C6 75 17 00, , , , \par
, 0x40a84e, int3, CC, , , , \par
, 0x40a84f, int3, CC, , , , \par
, 0x40a850, push esi, 56, , , , \par
, 0x40a851, mov esi,ecx, 8B F1, , , , \par
最終目標是使文件的每一行看起來像這樣
0x40a846, 0x 88 41 2B ,"mov [ecx+2bh],al",,,
我的主要問題是文件中的某些行僅包含源代碼的一部分,而其他行僅包含源代碼的一部分,這使我很難創建一個正則表達式來捕獲這兩行而不會偶然捕獲代碼字節。 我想使用捕獲組來重新排列每一行的信息。 下面是我到目前為止的腳本:
import csv
import string
import re, sys
file_to_change = 'testingthecodexlconverter.csv'
# = raw_input("Please specify what codexl file you would like to convert: ")
file1 = open(file_to_change, 'r+')
with file1 as f:
for line in f:
line = line[2:-12]
line = line.rstrip('\n') + ',,'
# mo = re.search(r'(.*?),.*?.*?,.*?(.*?),.*?.*?,.*?(.*?),.*?.*?,.*?(.*?)', line)
#mo = re.search(r'(.*?),.*?(.*?,.*?.*?,).*?.*?,.*?(.*?),.*?.*?,.*?(.*?)', line)
mo = re.search(r'(.*?),.*?(.*?.*?,\S*?,).*?.*?.*?,.*?(.*?),', line)
if mo:
print(mo.group(2))
有人可以幫我嗎?
您可以按照逗號分隔的方式標記行,然后在打印時將其重新添加
file_to_change = 'testingthecodexlconverter.csv'
file1 = open(file_to_change, 'r+')
with file1 as f:
for line in f:
line = line[2:-12]
tokens = line.split(',')
# if column index 3 is empty then print without formatting for
# unnecessary space.
if not tokens[3]:
print(tokens[0] + ", " + tokens[2].strip(" ") + ", " + tokens[1] + ",,,")
else:
print(tokens[0] + "," + tokens[3] + ", " + tokens[2].strip(" ") + ", " + tokens[1] + ",,,")
這將以以下格式打印:
0x40a846, 88 41 2B, al, mov [ecx+2bh],,,
0x40a849, E9 C6 75 17 00, jmp $+001775cbh (0x581e14),,,
0x40a84e, CC, int3,,,
0x40a84f, CC, int3,,,
0x40a850, 56, push esi,,,
0x40a851, 8B F1, ecx, mov esi,,,
我會使用pandas
並根據您的需要重新排列列,因為它們似乎采用了合理的csv
格式。 此方法還使您可以可視化在編輯時如何在csv中處理數據:
import pandas as pd
df = pd.read_csv('inputCSV.csv', header=None).fillna('')
df = df.astype(str)
out = df[[4,1,2]].to_csv(index=False, header=False, coding='utf-8', lineterminator='\r\n', mode='wb')
您在每個單獨的列中使用哪種數據格式的問題還不清楚。
我相信您在輸入的csv文件中可能缺少逗號。 我的建議是搜索這些缺失的逗號,並將其添加為具有正確格式的輸入文件。
最快的方法當然是通過使用.split()
如上所述分割字符串,但是您似乎不確定自己在做什么,因此我建議對pandas
進行解析。
您可以使用已包含但尚未使用的csv模塊。
import csv
file_path = 'test.csv'
with open(file_path) as csvfile:
reader = csv.reader(csvfile)
writer = csv.writer(open('tempfile.csv', 'w'), delimiter=',')
for row in reader:
new_row = [e.strip() for e in row if len(e.strip()) > 0]
# The new row should have the first element, then the last,
# followed by everything else that wasn't empty.
new_row = [new_row[0], new_row[-1]] + new_row[1:-1]
writer.writerow(new_row)
新的csv文件如下所示:
0x40a846,88 41 2B,mov [ecx+2bh],al
0x40a849,E9 C6 75 17 00,jmp $+001775cbh (0x581e14)
0x40a84e,CC,int3
0x40a84f,CC,int3
0x40a850,56,push esi
0x40a851,8B F1,mov esi,ecx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.