tablev2.go 25 KB

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