我正在嘗試撰寫一個 JSON 檔案,其中包含來自這樣的文本的匹配詞
servicepoint ? 200135644 watchid ? 7038842
所以每個 servicepoint 和 watchid 將只使用以下代碼插入到 Object 表中一次:
function readfile() {
Tesseract.recognize('form.png', 'ara', {
logger: m => console.log(m)
}).then(({ data: { text } }) => {
console.log(text); /* this line here */
var obj = {
table: []
};
const info = ['servicepoint', 'watchid'];
for (k = 0; k < info.length; k ) {
var result = text.match(new RegExp(info[k] '\\s (\\w )'))[1];
obj.table.push({
servicepoint: /* Here i want to insert the number after servicepoint*/ ,
watchid: /*also i want to insert the number after watchid to the Object table*/
});
}
var json = JSON.stringify(obj); /* converting the object table to json file*/
var fs = require('fs'); /* and then write json file contians the data*/
fs.writeFile('myjsonfile.json', json, 'utf8', callback);
})
};
uj5u.com熱心網友回復:
從我上面的評論之一......
甚至可以洗掉u nicode 標志并將上述模式轉換回
/servicepoint\W (\w )/非常接近 OP 原始代碼的模式。OP 只需\\s要用\\W
除了提議的模式更改之外,我還將 OP 的thenables更改為更清晰的任務,例如將檔案讀取與僅資料決議/提取與json-conversion/writing分開。
我還想說明,OP 所需data.table的基于格式不能是陣列,而必須是純鍵值結構(物件),因為可以聚合單個物件(在迭代屬性名稱時每次一個條目)或僅將單個屬性項(在迭代屬性名稱時一次項)推送到陣列中。(OP 會嘗試創建一個多條目物件,但也會推送它。)
下一個提供的代碼顯示了該方法。該實作遵循 OP 的原始代碼。它只是使用 async-await 語法并模擬/偽造檔案讀寫程序。
async function readFile(fileName) {
console.log({ fileName });
// return await Tesseract.recognize(fileName, 'ara', {
//
// logger: m => console.log(m)
// });
// fake it ...
return (await new Promise(resolve =>
setTimeout(
resolve,
1500,
{ data: { text: 'servicepoint ? 200135644 watchid ? 7038842'} }
)
));
}
/*async */function parseDataFromTextAndPropertyNames(text, propertyNames) {
console.log({ text, propertyNames });
return propertyNames
.reduce((table, key) =>
Object.assign(table, {
[ key ]: RegExp(`${ key }\\W (\\w )`)
.exec(text)?.[1] ?? ''
}), {});
}
async function writeParsedTextDataAsJSON(fileName, table) {
console.log({ table });
// const fs = require('fs');
// fs.writeFile(fileName, JSON.stringify({ table }), 'utf8', callback);
// fake it ...
return (await new Promise(resolve =>
setTimeout(() => {
console.log({ fileName, json: JSON.stringify({ table }) });
resolve({ success: true });
}, 1500)
));
}
console.log('... running ...');
(async () => {
const { data: { text } } = await readFile('form.png');
const data = /*await*/
parseDataFromTextAndPropertyNames(text, ['servicepoint', 'watchid']);
const result = await writeParsedTextDataAsJSON('myjsonfile.json', data);
console.log({ result });
})();
.as-console-wrapper { min-height: 100%!important; top: 0; }
uj5u.com熱心網友回復:
您可以使用String.match為您的兩個鍵獲取所需的變數值:“servicepoint”和“watchid”。
我建議使用這種匹配模式來獲取您的兩個資料點。
然后您需要創建 JSON 并將其字串化,為您提供如下內容:{servicepoint: 1323, watchid: 234}
我假設您有很多這樣的行,因此您需要將每個 JSON 鍵值添加到一個陣列中。然后,您可以JSON.stringify(dataArray)生成有效的 JSON 文本以寫入檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491857.html
標籤:javascript 正则表达式 解析 文本 匹配
上一篇:在Makefile中決議數字
