tablev2.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  1. package pretreated
  2. //定义表格对象
  3. import (
  4. "fmt"
  5. u "jy/util"
  6. "log"
  7. qutil "qfw/util"
  8. "regexp"
  9. "strings"
  10. "sync"
  11. "github.com/PuerkitoBio/goquery"
  12. )
  13. //所有中标候选人只取第一个
  14. type TableResult struct {
  15. Id interface{} //信息id
  16. Toptype string //信息类型
  17. Itype int //1全文 2是块
  18. BlockTag string //块标签
  19. Html string
  20. Tabs []*Table //子表集合,子表中包含标准化kv或原始kv
  21. GoqueryTabs []*goquery.Selection //goquery对象
  22. TableSize int //子表的个数0,1,n
  23. IsMultiPackage bool //是否有子包
  24. PackageMap *SortMap //子包对象的sortmap,含标准化过的
  25. SortKV *SortMap //全局KVmap值,标准化处理过的
  26. SortKVWeight map[string]int //全局KVmap值,标准化处理过的
  27. WinnerOrder []map[string]interface{}
  28. BrandData [][]map[string]string //品牌抽取结果
  29. HasKey int //有key
  30. HasBrand int //有品牌
  31. HasGoods int //有商品
  32. RuleBlock *u.RuleBlock
  33. }
  34. //快速创建TableResult对象
  35. func NewTableResult(Id interface{}, Toptype, BlockTag, con string, Itype int, ruleBlock *u.RuleBlock) *TableResult {
  36. return &TableResult{
  37. Id: Id,
  38. Toptype: Toptype,
  39. Html: con,
  40. Itype: Itype,
  41. BlockTag: BlockTag,
  42. Tabs: []*Table{},
  43. GoqueryTabs: []*goquery.Selection{},
  44. PackageMap: NewSortMap(),
  45. SortKV: NewSortMap(),
  46. SortKVWeight: map[string]int{},
  47. RuleBlock: ruleBlock,
  48. }
  49. }
  50. //td节点
  51. type TD struct {
  52. Goquery *goquery.Selection //文本对象
  53. TR *TR //所属TR对象
  54. LeftNode *TD //左临节点
  55. TopNode *TD //上临节点
  56. RightNode *TD //右节点
  57. BottomNode *TD //下节点
  58. Val string //值
  59. Text string //原始串
  60. SortKV *SortMap //存放kv值
  61. Html string //html值
  62. BH bool //是否是表头
  63. MustBH bool //不能修改的表头
  64. StandardKey string //标准表头
  65. Colspan int //合并列
  66. Rowspan int //合并行
  67. StartCol int //起始列
  68. EndCol int //终止列
  69. StartRow int //起始行
  70. EndRow int //终止行
  71. ColPos int //当前在TR中的位置
  72. HeadTd *TD //(是val元素)k节点
  73. KVDirect int //键-值方向,0未知,1横 2纵//指值和k的方向
  74. KeyDirect int //k方向,k纵值横,k横值纵 1横 2纵
  75. SonTds []*TD //(是key元素)值节点数组
  76. SonTableResult *TableResult //子值表格集
  77. ArrVal []string //数组值,当是左临元素是合并行的元素时!
  78. Valtype string //"BO=中标人顺序"
  79. }
  80. var submatchreg = regexp.MustCompile(`((?:[一二三四五六七八九十0-10]+[、])([\\S]{4,12})|([\\S]{2,12}))[::]([\\S]{5,60})([一二三四五六七八九]+[、])?`)
  81. var BHKey = regexp.MustCompile(`^[^,,;:。、.]{2,8}.{0,3}[::].+$`)
  82. var dwReg = regexp.MustCompile("单位[::/ \\s\u3000\u2003\u00a0\\n]*([万亿元]+)")
  83. func NewTD(Goquery *goquery.Selection, tr *TR, table *Table) *TD {
  84. defer qutil.Catch()
  85. td := &TD{
  86. ArrVal: []string{},
  87. Goquery: Goquery,
  88. SonTds: []*TD{},
  89. TR: tr,
  90. SortKV: NewSortMap(),
  91. }
  92. colspan, rowspan := 0, 0
  93. col, bcol := td.Goquery.Attr("colspan")
  94. if bcol {
  95. colspan = qutil.IntAllDef(col, 1)
  96. }
  97. if colspan == 0 {
  98. colspan = 1
  99. }
  100. row, brow := td.Goquery.Attr("rowspan")
  101. if brow {
  102. rowspan = qutil.IntAllDef(row, 1)
  103. }
  104. if rowspan == 0 {
  105. rowspan = 1
  106. }
  107. td.Colspan, td.Rowspan = colspan, rowspan //合并列,合并行
  108. td.Html, _ = td.Goquery.Html() //html值
  109. ht := td.Goquery.ChildrenFiltered("table") //获取td的table
  110. bsontable := false //默认td中没有table
  111. txt := ""
  112. //子table处理合并
  113. if ht.Size() > 0 {
  114. //qutil.Debug("有子表格")
  115. txt = TextAfterRemoveTable(td.Html)
  116. td.tdHasTable(&bsontable, tr, table) //处理td中的table,块标签处理,子表解析集处理
  117. } else {
  118. txt = strings.TrimSpace(td.Goquery.Text())
  119. }
  120. text := dwReg.ReplaceAllString(u.TrimLRAll(txt, ""), "$1")
  121. td.Val = text //值
  122. td.Text = txt //原始串
  123. //对td单元格值判断是否是表头和根据td内容长度进行分块处理
  124. td.tdIsHb(tr, table, bsontable)
  125. bhead := false
  126. if td.TR.RowPos == 0 { //第一行
  127. if td.Goquery.Closest("thead").Size() == 1 && !bsontable { //如果是thead确定为k值表头
  128. bhead = true
  129. }
  130. }
  131. if bhead && !bsontable {
  132. td.BH = true
  133. td.KeyDirect = 1 //k方向,k纵值横,k横值纵 1横 2纵
  134. td.KVDirect = 2 //键-值方向,0未知,1横 2纵//指值和k的方向
  135. }
  136. //u.Debug(td.BH, td.Val)
  137. return td
  138. }
  139. //处理td中的table,块标签处理,子表解析集处理
  140. func (td *TD) tdHasTable(bsontable *bool, tr *TR, table *Table) {
  141. ts := td.TR.Table.TableResult
  142. tabs, _ := ComputeConRatio(td.Html, 2) //计算表格占比
  143. if len(tabs) > 0 {
  144. (*bsontable) = true
  145. stag := ts.BlockTag //块标签
  146. if stag == "" {
  147. var tdleft *TD
  148. if len(tr.TDs) > 0 {
  149. tdleft = tr.TDs[len(tr.TDs)-1]
  150. if tdleft.BH {
  151. //u.Debug(tdleft.Val),如果不存在就是上一行的
  152. stag = tdleft.Val
  153. }
  154. } else if len(tr.Table.TRs) > 0 {
  155. lasttr := tr.Table.TRs[len(tr.Table.TRs)-1]
  156. str := ""
  157. for _, td3 := range lasttr.TDs {
  158. str += td3.Val
  159. if len([]rune(str)) > 14 {
  160. str = ""
  161. break
  162. }
  163. }
  164. stag = str
  165. }
  166. sonts := AnalyTableV2(tabs, ts.Toptype, stag, td.Html, 2, ts.Id, table.TableResult.RuleBlock) //又一次调用解析表格入口
  167. td.BH = false
  168. td.SonTableResult = sonts
  169. //for _, k := range sonts.SortKV.Keys {
  170. //u.Debug(k, sonts.SortKV.Map[k])
  171. // td.TR.Table.StandKV[k] = sonts.SortKV.Map[k].(string)
  172. // td.TR.Table.StandKVWeight[k] = sonts.SortKVWeight[k]
  173. //}
  174. //增加brand (子表)
  175. //fmt.Println("sonsHasKey=============", sonts.HasKey)
  176. //fmt.Println("sonsHasGoods========", sonts.HasGoods)
  177. //fmt.Println("sonsHasBrand========", sonts.HasBrand)
  178. if sonts.HasKey != 0 {
  179. td.TR.Table.TableResult.HasKey = sonts.HasKey
  180. }
  181. if sonts.HasGoods != 0 {
  182. td.TR.Table.TableResult.HasGoods = sonts.HasGoods
  183. }
  184. if sonts.HasBrand != 0 {
  185. td.TR.Table.TableResult.HasBrand = sonts.HasBrand
  186. }
  187. if sonts.BrandData != nil && len(sonts.BrandData) > 0 { //子table
  188. for _, v := range sonts.BrandData {
  189. if len(v) > 0 {
  190. td.TR.Table.TableResult.BrandData = append(td.TR.Table.TableResult.BrandData, v)
  191. }
  192. }
  193. }
  194. if sonts.WinnerOrder != nil && len(sonts.WinnerOrder) > 0 {
  195. td.TR.Table.TableResult.WinnerOrder = sonts.WinnerOrder
  196. }
  197. if sonts.IsMultiPackage {
  198. td.TR.Table.BPackage = true
  199. tb1 := td.TR.Table.BlockPackage
  200. for k, v := range sonts.PackageMap.Map {
  201. v1 := v.(*u.BlockPackage)
  202. if tb1.Map[k] == nil {
  203. tb1.AddKey(k, v)
  204. } else {
  205. bp := tb1.Map[k].(*u.BlockPackage)
  206. if bp != nil && v1.TableKV != nil && v1.TableKV.Kv != nil {
  207. for k2, v2 := range v1.TableKV.Kv {
  208. if bp.TableKV.Kv != nil && bp.TableKV.Kv[k2] == "" {
  209. bp.TableKV.Kv[k2] = v2
  210. bp.Text += fmt.Sprintf("%v:%v\n", k2, v2)
  211. }
  212. }
  213. }
  214. }
  215. }
  216. //u.Debug(fmt.Sprintf("%v", td.TR.Table.BlockPackage.Map["1"]))
  217. }
  218. }
  219. }
  220. }
  221. //对td单元格值判断是否是表头和根据td内容长度进行分块处理
  222. func (td *TD) tdIsHb(tr *TR, table *Table, bsontable bool) {
  223. lenval := len([]rune(td.Val)) //经过处理的td内容长度
  224. //if lentxt > 9 {
  225. //td.KV = GetKVAll(txt, "")
  226. ub := []*u.Block{}
  227. //经过处理的td内容长度大于50,划块,分包
  228. if lenval > 50 { //看是否划块
  229. //u.Debug(txt)
  230. ub, _ = DivideBlock(td.Text, 2, table.TableResult.RuleBlock) //对td的原始值
  231. //看是否划块
  232. if len(ub) > 0 {
  233. colonKvWeight := map[string]int{}
  234. spaceKvWeight := map[string]int{}
  235. for _, bl := range ub {
  236. //冒号kv
  237. for bl_ck, bl_cv := range bl.ColonKV.Kv {
  238. if td.SortKV.Map[bl_ck] == nil || bl.ColonKV.KvTag[bl_ck].Weight >= colonKvWeight[bl_ck] {
  239. colonKvWeight[bl_ck] = bl.ColonKV.KvTag[bl_ck].Weight
  240. td.SortKV.AddKey(bl_ck, bl_cv)
  241. }
  242. }
  243. //空格kv
  244. for bl_sk, bl_sv := range bl.SpaceKV.Kv {
  245. if td.SortKV.Map[bl_sk] == nil || bl.SpaceKV.KvTag[bl_sk].Weight >= spaceKvWeight[bl_sk] {
  246. spaceKvWeight[bl_sk] = bl.SpaceKV.KvTag[bl_sk].Weight
  247. td.SortKV.AddKey(bl_sk, bl_sv)
  248. }
  249. }
  250. }
  251. }
  252. //
  253. blockPackage := map[string]*u.BlockPackage{}
  254. isFindPkg := true
  255. /*if td.ColPos-1 >= 0 && excludeKey.MatchString(tr.TDs[td.ColPos-1].Text) {
  256. isFindPkg = false
  257. } else if len(tr.TDs) > 0 {
  258. tdleft = tr.TDs[len(tr.TDs)-1]
  259. if tdleft.BH && excludeKey.MatchString(tr.TDs[td.ColPos-1].Text) {
  260. isFindPkg = false
  261. }
  262. }*/
  263. if len(tr.TDs) > 0 {
  264. tdleft := tr.TDs[len(tr.TDs)-1]
  265. if tdleft.BH && excludeKey.MatchString(tdleft.Text) { //(涉及包号|包件号?|项目标号|规格|型号|招标范围|业绩|废标)|(^编号$)|([^包段标]编号)
  266. isFindPkg = false
  267. }
  268. }
  269. if isFindPkg {
  270. if len(ub) > 0 {
  271. blockPackage = FindPackageFromBlocks(&ub, "") //从块里面找分包
  272. } else {
  273. blockPackage = FindPackageFromText("", td.Val) //从正文里面找分包
  274. }
  275. }
  276. if len(blockPackage) > 0 {
  277. table.BPackage = true
  278. for bp_k, bp_v := range blockPackage {
  279. var bp *u.BlockPackage
  280. if table.TableResult.PackageMap.Map[bp_k] == nil {
  281. bp = bp_v
  282. } else {
  283. bp = table.TableResult.PackageMap.Map[bp_k].(*u.BlockPackage)
  284. bp.Text += "\n" + bp_v.Text
  285. }
  286. if bp.TableKV == nil {
  287. bp.TableKV = u.NewJobKv()
  288. }
  289. for k2, v2 := range bp_v.ColonKV.Kv {
  290. if bp.TableKV.Kv[k2] == "" {
  291. bp.TableKV.Kv[k2] = v2
  292. }
  293. }
  294. for k2, v2 := range bp_v.SpaceKV.Kv {
  295. if bp.TableKV.Kv[k2] == "" {
  296. bp.TableKV.Kv[k2] = v2
  297. }
  298. }
  299. table.TableResult.PackageMap.Map[bp_k] = bp
  300. }
  301. }
  302. }
  303. //经过处理的td内容长度小于50,冒号kv,td表头
  304. if lenval < 50 {
  305. // td.SortKV = FindKv(text, "")
  306. kvTitle := ""
  307. if len(td.TR.TDs) > 0 {
  308. kvTitle = td.TR.TDs[len(td.TR.TDs)-1].Val
  309. }
  310. /*
  311. 预算总价
  312. (人民币:元)
  313. */
  314. if td.Text != "" && strings.Contains(td.Text, "预算总价") && (strings.Contains(td.Text, "(") || strings.Contains(td.Text, "(")) {
  315. tagindex := 0
  316. if tagindex = strings.Index(td.Text, "("); tagindex <= 0 {
  317. tagindex = strings.Index(td.Text, "(")
  318. }
  319. td.SortKV.AddKey(strings.TrimSpace(td.Text[:tagindex]), strings.TrimSpace(td.Text[tagindex:])) //存放kv值
  320. td.BH = true
  321. }
  322. _, resm := colonkvEntity.entrance(td.Val, kvTitle, nil, 3) //td冒号kv
  323. for k, v := range resm {
  324. td.SortKV.AddKey(k, v) //存放kv值
  325. }
  326. //u.Debug(td.SortKV.Keys, "-------2--------------------------------")
  327. // td.SortKV = FindKv(text, "") //GetKvFromtxt(text, "")
  328. //resm := GetKVAll(text, "")
  329. if len(td.SortKV.Keys) > 0 {
  330. //td.KVDirect = 3 //不当头也不当值,忽略
  331. if len(td.SortKV.Keys) == 1 && BHKey.MatchString(td.Val) && !MultiReg.MatchString(td.Val) {
  332. td.Val = td.SortKV.Keys[0]
  333. td.BH = true
  334. }
  335. } else if !bsontable {
  336. txt := repSpace.ReplaceAllString(td.Val, "")
  337. btw, must, _, _, repl := CheckHeader(txt)
  338. if lenval > 15 {
  339. btw = false
  340. }
  341. if strings.Contains(td.Val, "个项目") {
  342. must = false
  343. btw = false
  344. }
  345. td.Valtype = repl
  346. td.MustBH = must
  347. td.BH = btw
  348. }
  349. } else if len(ub) == 0 {
  350. //之前这里没加判断,现在加上判断,造成分块之后的kv被覆盖掉
  351. //u.Debug("----\n\n\n", txt, "\n\n\n----")
  352. //u.Debug(GetKVAll(txt, ""))
  353. /*
  354. subVal := submatchreg.FindAllStringSubmatch(txt, -1)
  355. if len(subVal) > 0 {
  356. for _, subv1 := range subVal {
  357. if len(subv1) == 6 {
  358. tr.Table.SortKV.AddKey(If(subv1[2] == "", subv1[3], subv1[2]).(string), subv1[4])
  359. //tr.Table.SortKV.AddKey(subv1[1], subv1[2])
  360. }
  361. }
  362. }
  363. */
  364. td.SortKV = FindKv(td.Val, "", 2)
  365. // td.LeftNode.Val
  366. // for _, vvv := range *td.TR {
  367. // u.Debug(">>>>>")
  368. // }
  369. kvTitle := ""
  370. if len(td.TR.TDs) > 0 {
  371. kvTitle = td.TR.TDs[len(td.TR.TDs)-1].Val
  372. }
  373. _, resm := colonkvEntity.entrance(td.Val, kvTitle, nil, 2) //获取冒号kv入口
  374. for k, v := range resm {
  375. td.SortKV.AddKey(k, v)
  376. }
  377. }
  378. }
  379. func (t *Table) Print() {
  380. for row, trs := range t.TRs {
  381. for col, td := range trs.TDs {
  382. log.Println(row, col, td.Val, td.BH, td.SortKV.Map)
  383. }
  384. }
  385. }
  386. type TR struct {
  387. TDs []*TD
  388. TopTR *TR //上临行
  389. BottomTR *TR //下临行
  390. Table *Table //所属表格对象
  391. RowPos int //当前在第几行
  392. //-----计算
  393. MaxRow int //最大跨行 Max(td.StartRow-td.EndRow)
  394. MinRow int //最小跨行
  395. StartRow int //起始行
  396. EndRow int //结束行
  397. MaxCol int //最大列
  398. MinCol int //最小列
  399. StartCol int //起始列
  400. EndCol int //结束列
  401. BDiffSpanRow bool //起始行,行中有没有不同跨行 - - - = -
  402. BDiffSpanCol bool //起始列,列中有没有不同跨列 |
  403. }
  404. func NewTR(Table *Table) *TR {
  405. return &TR{
  406. TDs: []*TD{},
  407. Table: Table,
  408. }
  409. }
  410. func (tr *TR) AddTD(td *TD) {
  411. /**对跨行没有意义
  412. if len(tr.TDs) > 0 {
  413. td.LeftNode = tr.TDs[len(tr.TDs)-1]
  414. tr.TDs[len(tr.TDs)-1].RightNode = td
  415. }
  416. **/
  417. td.ColPos = len(tr.TDs)
  418. tr.TDs = append(tr.TDs, td)
  419. }
  420. /*-- START --- 处理表头概率开始 -------*/
  421. type pos struct {
  422. Max int
  423. Min int
  424. }
  425. type TDRationScope struct {
  426. Rationmap map[*pos]float32
  427. Tdmap map[*pos][]*TD
  428. Poss []*pos
  429. Parentkey string
  430. }
  431. func NewTDRationScope(key string) *TDRationScope {
  432. return &TDRationScope{map[*pos]float32{}, map[*pos][]*TD{}, []*pos{}, key}
  433. }
  434. func (tdr *TDRationScope) GetPos(td *TD) (poss *pos) {
  435. k1 := tdr.Parentkey[:1]
  436. m1, m2 := td.StartRow, td.EndRow
  437. if k1 == "r" {
  438. m1, m2 = td.StartCol, td.EndCol
  439. }
  440. for _, v := range tdr.Poss {
  441. if v.Max >= m2 && v.Min <= m1 {
  442. poss = v
  443. return
  444. }
  445. }
  446. return
  447. }
  448. func (tdr *TDRationScope) GetTDRation(td *TD) (ration float32, tds []*TD) {
  449. poss := tdr.GetPos(td)
  450. if poss != nil {
  451. ration = tdr.Rationmap[poss]
  452. tds = tdr.Tdmap[poss]
  453. }
  454. return
  455. }
  456. func (tdr *TDRationScope) Addtd(td *TD) {
  457. k1 := tdr.Parentkey[:1]
  458. m1, m2 := td.StartRow, td.EndRow
  459. if k1 == "r" {
  460. m1, m2 = td.StartCol, td.EndCol
  461. }
  462. bfind := false
  463. for _, v := range tdr.Poss {
  464. if m1 == v.Max+1 { //找到
  465. bfind = true
  466. v.Max = m2
  467. tdr.Tdmap[v] = append(tdr.Tdmap[v], td)
  468. break
  469. }
  470. }
  471. if !bfind {
  472. pos1 := &pos{m2, m1}
  473. tdr.Tdmap[pos1] = []*TD{td}
  474. tdr.Poss = append(tdr.Poss, pos1)
  475. }
  476. }
  477. /*-- END --- 处理表头概率 -------*/
  478. //table表格
  479. type Table struct {
  480. Brule bool //是否规则
  481. TRs []*TR
  482. BFirstRow bool
  483. RowNum int //行数
  484. ColNum int //列数
  485. TDNum int //td个数
  486. BPackage bool //是否有包
  487. SortKV *SortMap //带排序的KV值
  488. StandKV map[string]string //过滤后的标准化kv
  489. StandKVWeight map[string]int //过滤后的标准化kv
  490. StandRuleKV map[string]string //过滤后的规则kv
  491. kvscope map[int]map[int][]*TD //sortkey第几个元素的的第几个值的结束位置
  492. kTD map[int]*TD //根据索引找到key的TD元素
  493. SonTables []*Table //孩子表集合
  494. Tag string //表格的标签
  495. Desc string //表格描述内容
  496. Goquery *goquery.Selection //表格的goquery对象
  497. Html string //所属的文本内容
  498. BlockPackage *SortMap //子包数组
  499. TableResult *TableResult //父元素
  500. StartAndEndRation map[string]*TDRationScope //同行或同列的概率,截断的单独起算
  501. StartAndEndRationKSort *SortMap
  502. WinnerOrder []map[string]interface{}
  503. BSplit bool //是否是有一个表拆分成的多个表
  504. BHeader bool //拆分表是否有表头
  505. BrandData [][]map[string]string //品牌抽取结果
  506. HasKey int //有key
  507. HasBrand int //有品牌
  508. HasGoods int //有商品
  509. }
  510. func NewTable(Html string, TableResult *TableResult, tab *goquery.Selection) *Table {
  511. return &Table{
  512. Html: Html,
  513. SortKV: NewSortMap(),
  514. StandKV: map[string]string{},
  515. StandKVWeight: map[string]int{},
  516. kvscope: map[int]map[int][]*TD{},
  517. kTD: map[int]*TD{},
  518. SonTables: []*Table{},
  519. Goquery: tab,
  520. TRs: []*TR{},
  521. TableResult: TableResult,
  522. StartAndEndRation: map[string]*TDRationScope{},
  523. StartAndEndRationKSort: NewSortMap(),
  524. BlockPackage: NewSortMap(),
  525. }
  526. }
  527. func (t *Table) AddTR(tr *TR) {
  528. if len(tr.TDs) > 0 {
  529. if len(t.TRs) > 0 {
  530. tr.TopTR = t.TRs[len(t.TRs)-1]
  531. t.TRs[len(t.TRs)-1].BottomTR = tr
  532. }
  533. tr.RowPos = len(t.TRs)
  534. t.TRs = append(t.TRs, tr)
  535. }
  536. }
  537. func (t *Table) InsertTR(tr *TR) {
  538. if len(tr.TDs) > 0 {
  539. if len(t.TRs) > 0 {
  540. t.TRs[0].TopTR = tr
  541. }
  542. tr.RowPos = 0
  543. for _, _tr := range t.TRs {
  544. _tr.RowPos += 1
  545. }
  546. t.TRs = append([]*TR{tr}, t.TRs...)
  547. }
  548. }
  549. //支持排序的map
  550. type SortMap struct {
  551. Index map[string]int
  552. Keys []string
  553. Map map[string]interface{}
  554. Lock sync.Mutex
  555. }
  556. //快速创建排序map
  557. func NewSortMap() *SortMap {
  558. return &SortMap{
  559. Index: map[string]int{},
  560. Keys: []string{},
  561. Map: map[string]interface{}{},
  562. }
  563. }
  564. //增加值
  565. var NullVal = regexp.MustCompile("^[/无,.。;、附]+$|^详见.{2,8}$|(详?见)?附(件|图)")
  566. func (s *SortMap) AddKey(key string, val interface{}) {
  567. //判断val
  568. // if v, ok := val.(string); ok && NullVal.ReplaceAllString(u.TrimLRSpace(v, ""), "") == "" {
  569. // return
  570. // }
  571. s.Lock.Lock()
  572. defer s.Lock.Unlock()
  573. //重复
  574. if s.Map[key] == nil {
  575. s.Index[key] = len(s.Keys)
  576. s.Keys = append(s.Keys, key)
  577. }
  578. s.Map[key] = val
  579. }
  580. //增加值
  581. func (s *SortMap) ReplaceKey(key string, val interface{}, replacekey string) {
  582. s.Lock.Lock()
  583. defer s.Lock.Unlock()
  584. //重复
  585. v := s.Index[replacekey]
  586. s.Index[key] = v
  587. delete(s.Index, replacekey)
  588. s.Keys = append(s.Keys[:v], append([]string{key}, s.Keys[v+1:]...)...)
  589. delete(s.Map, replacekey)
  590. s.Map[key] = val
  591. }
  592. //删除值
  593. func (s *SortMap) RemoveKey(key string) {
  594. s.Lock.Lock()
  595. defer s.Lock.Unlock()
  596. delete(s.Map, key)
  597. pos := s.Index[key]
  598. delete(s.Index, key)
  599. if len(s.Keys) > 0 {
  600. s.Keys = func() []string {
  601. newkeys := []string{}
  602. if len(s.Keys) > 1 {
  603. if pos == 0 {
  604. newkeys = append(newkeys, s.Keys[1:]...)
  605. //每一个都减一
  606. for k, v := range s.Index {
  607. s.Index[k] = v - 1
  608. }
  609. } else if pos == len(s.Keys) {
  610. newkeys = append(newkeys, s.Keys[:pos]...)
  611. } else {
  612. tmp := s.Keys[pos+1:]
  613. newkeys = append(append(newkeys, s.Keys[:pos]...), tmp...)
  614. for _, v := range tmp {
  615. s.Index[v] -= 1
  616. }
  617. }
  618. }
  619. return newkeys
  620. }()
  621. }
  622. }
  623. //判断表头是key的对象
  624. type TableKeyV1 struct {
  625. TMap map[string]interface{}
  626. TReg []*regexp.Regexp
  627. TRegReplStr []string
  628. }
  629. //判断表头时用到的顺序 正文、结果表头、正常表头
  630. var THeadStr = []string{
  631. "con",
  632. "jghead",
  633. "normalhead",
  634. }
  635. //存放敏感词
  636. var TKMaps = map[string]*TableKeyV1{}
  637. //过滤所有非汉字内容
  638. var filterThText = regexp.MustCompile("([((【\\[].*[))】\\]])|([^0-9a-zA-Z\\p{Han}]+)")
  639. var tLock = sync.Mutex{}
  640. //matchStro为tablev1.json文件中的key,txt为表格的内容也可以是表格的标签
  641. //主要实现表格是否是表头的判断,表格是否有用的判断(如人员情况等是无用的)
  642. func CheckCommon(txt string, matchStr ...string) (res, must bool, stype, reg, repl string) {
  643. txt = filterThText.ReplaceAllString(txt, "")
  644. stype = "con"
  645. if len([]rune(txt)) < 30 {
  646. tLock.Lock()
  647. defer tLock.Unlock()
  648. if len(TKMaps) == 0 {
  649. for k, v := range u.TableK1 {
  650. tk := &TableKeyV1{
  651. map[string]interface{}{},
  652. []*regexp.Regexp{},
  653. []string{},
  654. }
  655. thMap := map[string]interface{}{}
  656. for _, v1 := range v {
  657. v1s := strings.Split(v1, "__")
  658. if len(v1s) == 2 {
  659. tk.TReg = append(tk.TReg, regexp.MustCompile(v1s[0]))
  660. tk.TRegReplStr = append(tk.TRegReplStr, v1s[1])
  661. } else {
  662. key := v1
  663. nowMap := &thMap
  664. for i := 0; i < len(key); i++ {
  665. kc := key[i : i+1]
  666. if v, ok := (*nowMap)[kc]; ok {
  667. nowMap, _ = v.(*map[string]interface{})
  668. } else {
  669. newMap := map[string]interface{}{}
  670. newMap["Y"] = "0"
  671. (*nowMap)[kc] = &newMap
  672. nowMap = &newMap
  673. }
  674. if i == len(key)-1 {
  675. (*nowMap)["Y"] = "1"
  676. (*nowMap)["K"] = key
  677. //(*nowMap)["V"] = v
  678. }
  679. }
  680. }
  681. }
  682. tk.TMap = thMap
  683. TKMaps[k] = tk
  684. }
  685. }
  686. //先正则、后子串查找
  687. L1:
  688. for _, v := range matchStr {
  689. //u.Debug(v)
  690. for n, vreg := range TKMaps[v].TReg {
  691. if vreg.MatchString(txt) {
  692. //u.Debug(txt, v, vreg.String())
  693. reg = vreg.String()
  694. repl = TKMaps[v].TRegReplStr[n]
  695. if v != "con" {
  696. res = true
  697. if "M" == repl {
  698. must = true
  699. }
  700. }
  701. stype = v
  702. break L1
  703. }
  704. }
  705. //以下是敏感词子串查找匹配
  706. pos := 0
  707. thMap := TKMaps[v].TMap
  708. nowMap := &thMap
  709. for i := 0; i < len(txt); i++ {
  710. word := txt[i : i+1]
  711. nowMap, _ = (*nowMap)[word].(*map[string]interface{})
  712. if nowMap != nil { // 存在,则判断是否为最后一个
  713. if pos == 0 {
  714. pos = i
  715. }
  716. if "1" == qutil.ObjToString((*nowMap)["Y"]) {
  717. if v != "con" {
  718. res = true
  719. }
  720. stype = v
  721. pos = 0
  722. break L1
  723. }
  724. } else {
  725. nowMap = &thMap
  726. if pos > 0 {
  727. i = pos
  728. pos = 0
  729. }
  730. }
  731. }
  732. }
  733. return
  734. } else {
  735. return
  736. }
  737. }
  738. //根据td中的内容验证表头,根据tablev1.json中配置的三种规则(含正则和子串查找算法)
  739. func CheckHeader(txt string) (res, must bool, stype, reg, repl string) {
  740. return CheckCommon(txt, THeadStr...)
  741. }
  742. /**
  743. 计算表格占比,返回表格数组、占比
  744. con 文本
  745. strtype 1全文 2块文本
  746. **/
  747. func ComputeConRatio(con string, strtype int) (tabs []*goquery.Selection, ratio float32) {
  748. defer qutil.Catch()
  749. doc, _ := goquery.NewDocumentFromReader(strings.NewReader(con))
  750. cons := doc.Text()
  751. tables := doc.Find("table")
  752. doc = nil
  753. if tables.Size() > 0 {
  754. tabs = []*goquery.Selection{}
  755. for i := 0; i < tables.Size(); i++ {
  756. tmpt := tables.Eq(i)
  757. b := false
  758. for j := 0; j < len(tabs); j++ {
  759. if tabs[j].Contains(tmpt.Get(0)) {
  760. b = true
  761. }
  762. }
  763. if !b {
  764. tabs = append(tabs, tmpt)
  765. }
  766. }
  767. tlen := 0
  768. for _, t := range tabs {
  769. tlen += len(t.Text())
  770. }
  771. ratio = float32(tlen) / float32(len(cons))
  772. }
  773. /**
  774. if ratio < float32(0.992) {
  775. //取出排除表格之外的文本
  776. txt =getTextAfterRemoveTable(con)
  777. }
  778. **/
  779. return
  780. }
  781. //取出排除表格之外的文本
  782. func TextAfterRemoveTable(con string) string {
  783. doc2, _ := goquery.NewDocumentFromReader(strings.NewReader(con))
  784. doc2.Find("table").Remove()
  785. return doc2.Text()
  786. }
  787. func HtmlAfterRemoveTable(con string) string {
  788. doc2, _ := goquery.NewDocumentFromReader(strings.NewReader(con))
  789. doc2.Find("table").Remove()
  790. html, _ := doc2.Html()
  791. return html
  792. }
  793. func If(condition bool, trueVal, falseVal interface{}) interface{} {
  794. if condition {
  795. return trueVal
  796. }
  797. return falseVal
  798. }