如何根据重复的字符串将文件拆分为多个文件?

2024-04-29 09:43:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,希望根据字符串“async”将文件拆分为不同的文件。预期的输出有点混乱。我尝试使用一个单词作为键(“async”)来划分文件,但生成的文件具有其函数的第一行,并具有下面函数的上下文。例如,该文件是:

'use strict';
const shim = require('fabric-shim');
const util = require('util');

let Chaincode = class {
  async Init(stub) {
    let ret = stub.getFunctionAndParameters();
    console.info(ret);
    console.info('=========== Instantiated Marbles Chaincode ===========');
    return shim.success();
  }

  async Invoke(stub) {
    console.info('Transaction ID: ' + stub.getTxID());
    console.info(util.format('Args: %j', stub.getArgs()));

    let ret = stub.getFunctionAndParameters();
    console.info(ret);

    let method = this[ret.fcn];
    if (!method) {
      console.log('no function of name:' + ret.fcn + ' found');
      throw new Error('Received unknown function ' + ret.fcn + ' invocation');
    }
    try {
      let payload = await method(stub, ret.params, this);
      return shim.success(payload);
    } catch (err) {
      console.log(err);
      return shim.error(err);
    }
  }

  async initMarble(stub, args, thisClass) {
    if (args.length != 4) {
      throw new Error('Incorrect number of arguments. Expecting 4');
    }
    // ==== Input sanitation ====
    console.info('--- start init marble ---')
    if (args[0].lenth <= 0) {
      throw new Error('1st argument must be a non-empty string');
    }
    if (args[1].lenth <= 0) {
      throw new Error('2nd argument must be a non-empty string');
    }
    if (args[2].lenth <= 0) {
      throw new Error('3rd argument must be a non-empty string');
    }
    if (args[3].lenth <= 0) {
      throw new Error('4th argument must be a non-empty string');
    }
    let marbleName = args[0];
    let color = args[1].toLowerCase();
    let owner = args[3].toLowerCase();
    let size = parseInt(args[2]);
    if (typeof size !== 'number') {
      throw new Error('3rd argument must be a numeric string');
    }

    let marbleState = await stub.getState(marbleName);
    if (marbleState.toString()) {
      throw new Error('This marble already exists: ' + marbleName);
    }

    // ==== Create marble object and marshal to JSON ====
    let marble = {};
    marble.docType = 'marble';
    marble.name = marbleName;
    marble.color = color;
    marble.size = size;
    marble.owner = owner;

    await stub.putState(marbleName, Buffer.from(JSON.stringify(marble)));
    let indexName = 'color~name'
    let colorNameIndexKey = await stub.createCompositeKey(indexName, [marble.color, marble.name]);
    console.info(colorNameIndexKey);
    console.info('- end init marble');
  }

我试过这个:

import re 
import os
filetype = '.js'
result = ''
count = 0
start = 0
name = 'functions'
matchedLine = ''
stringToMatch = 'async' 
with open ('myjson.js', 'r') as f:
    for x in f.read().split("\n"):
            if stringToMatch in x:
                if (start == 1):
                    with open (name + str(count) + '.js', 'w') as opf:
                        matchedLine = x
                        opf.write(matchedLine + '\n' + result)
                        opf.close()
                        result = ''
                        print (count)
                        count+= 1
                        matchedLine = ''
                else:
                    start = 1     
            else:
                if (result == ''): 
                    result = x         
                else:
                    result = result + '\n' + x  

但是输出有点混乱 function0.js:

  async Invoke(stub) {
'use strict';
const shim = require('fabric-shim');
const util = require('util');

let Chaincode = class {
    let ret = stub.getFunctionAndParameters();
    console.info(ret);
    console.info('=========== Instantiated Marbles Chaincode ===========');
    return shim.success();
  }

function1.js:

  async initMarble(stub, args, thisClass) {
    console.info('Transaction ID: ' + stub.getTxID());
    console.info(util.format('Args: %j', stub.getArgs()));

    let ret = stub.getFunctionAndParameters();
    console.info(ret);

    let method = this[ret.fcn];
    if (!method) {
      console.log('no function of name:' + ret.fcn + ' found');
      throw new Error('Received unknown function ' + ret.fcn + ' invocation');
    }
    try {
      let payload = await method(stub, ret.params, this);
      return shim.success(payload);
    } catch (err) {
      console.log(err);
      return shim.error(err);
    }
  }

Tags: nameinfonewasyncifargserrorresult
2条回答

如果您的目标是将包含异步代码的所有部分分离到单独的文件中,那么您可以尝试的一种方法是先计算开放部分的花括号,然后计算关闭部分的花括号。为此,您可以设置一个变量,该变量对每个{正递增,对每个}负递增,例如(不是优化的/漂亮的,只是解释一下)

brackets = 0
buffer = ""
found_async = False
for line_of_code in code:
  if "async" in line_of_code:
    if "{" in line_of_code:
        brackets += 1
    if "}" in line_of_code:
        brackets -= 1

    buffer += line_of_code
    if brackets == 0:
         write_buffer_to_file_here
         buffer = ""

作为一个概念,这可能不会像现在这样起作用,但应该会让你了解我想说什么

一定有很多方法可以做到这一点。这里有一个:

import re

class Writer:
    def __init__(self):
        self._num = 0
        self._fh = None

    def close(self):
        if self._fh:
            self._fh.close()

    def start_file(self):
        self.close()
        self._fh = open("file{}.js".format(self._num), "w")
        self._num += 1

    def write(self, data):
        if self._fh:
            self._fh.write(data)


writer = Writer()

with open('myjson.js') as f:
    for line in f:
        if re.match(' *async ', line):
            writer.start_file()
        writer.write(line)
    writer.close()

相关问题 更多 >