tablev2.go 22 KB

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