上一篇文章中提到对solidity源代码的注释和空格的处理;有时候做数据处理时只需要一些指定的代码行,一些对实验无用的代码应该去掉,这样有助于我们队数据进行分析。在我们所做的实验中,我需要提取的是和call.value这个关键字相关的代码段,这里我们先进行了一些初步的处理,提取call.value的前10行代码和后10行代码。
(1)定位文件中call.value的位置
def find_location(filepath):
f = open(filepath, 'r')
lines = f.readlines()
f.close()
line_len = len(lines)
location = 0
for i in range(line_len):
if 'call.value' in lines[i]:
location = i
extract_selected_code(filepath, location)
对于一个文件,首先我们需要定位到call.value的位置,找到该位置之后,我们就可以提取该位置的前10行和后10行的代码了。
(2)提取指定的代码段
def extract_selected_code(filepath, location):
f = open(filepath, 'r')
lines = f.readlines()
f.close()
line_len = len(lines)
result = None
result1 = None
result2 = None
if location - 10 >= 0:
result1 = lines[location - 10:location]
print('前10行:', result1)
else:
result1 = lines[0:location]
print('前10行:', result1)
if location + 10 <= line_len:
result2 = lines[location:location + 10]
print('后10行:', result2)
else:
result2 = lines[location:line_len]
print('后10行:', result2)
result = result1 + result2
print(result)
newFilePath = '../train_data_V2/'
writeResult(newFilePath + filepath.split('/')[2], result)
在这里我们进行了一些小的处理,如果call.value的关键字在最前面或最后面,那么直接运行会获取不到代码段;由此,我们在这里加入了基本的判断,见(2)。