orange-text / orngText.py

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
"""
This module is used for text mining in Orange.

The following languages are supported:
bg - Bulgarian
cs - Czech
en - English
es - Spanish
et - Estonian
fr - French
ge - German
hr - Croatian
hu - Hungarian
it - Italian
ro - Romanian
sl - Slovenian
sr - Serbian
"""

"""
list(string) = tokenize(string)

>>> tokenize("Mico Mrkaic je isao po dlekom putu.")
["Mico", " ", "Mrkaic", " ", "je", " ", "isao" ," ", "po",  " ", "dlekom", " ", "putu", "."]

token = lemmatize(token)
text = lemmatize(text, lemmatizer=None)
list(token) = lemmatize(list(token), lemmatizer=None)

p = preprocess() # default english
p = preprocess(language="hrvatski")
print p.stopwords
p.stopwords = ['a', 'the']

p.lemmatize('idemo')
ici

p.lemmatize('idemo kuci')
'ici kuca'

p.lemmatize(['idemo','kuci'])
['ici','kuca']

p.removeStopwords(text)
p.removeStopwords(list(token))
p.removeStopwords(token) # returns token or None

print p.tokenize('I am the best.')
I am best.

table[0]['rijeci7']

encoding - tmt uvijek prima i vraca UTF8 string
da li je string ili lista je sugavo napravljeno
dokumentacija
dodati nove jezike
text je zadnji string atribut
from orngText import orngText - jel moze to bolje (proucit python pakete)

##supportedLangs = [('bg', 'Bulgarian'), ('cs', 'Czech'), ('en', 'English'), ('es', 'Spanish')\
##('et', 'Estonian'), ('fr', 'French'), ('ge', 'German'), ('hr', 'Croatian'),\
##('hu', 'Hungarian'), ('it', 'Italian'), ('ro', 'Romanian'), ('sl', 'Slovenian'),\
##('sr', 'Serbian')]

"""

import sys
if sys.version < "2.4":
   from sets import Set
   set = Set
from xml.sax import handler, make_parser
import os.path
import re
import orange
import orngTextWrapper
import types
import warnings
from math import log,exp

TEXTMETAID = 7

def getTextAttributePos(data, textAttribute=None, issueWarning=True):
    """return a position of a last string attribute,
    if textAttribute not None checks if this is string,
    return None if no string attribute found"""
    if textAttribute not in data.domain:
        textAttribute = None
    if textAttribute != None and data.domain[textAttribute].varType == orange.VarTypes.String:
        return data.domain.attributes.index(data.domain[textAttribute])
    else:
        atts = list(data.domain.attributes)
        atts.reverse()
        for a in atts:
            if a.varType == orange.VarTypes.String:
                return data.domain.attributes.index(data.domain[a])
    if issueWarning:
        warnings.warn("Data file includes no text attribute")
    return None


def loadWordSet(f):
    try:
       f = open(f, 'r')
    except:
       return set([])
    setW = set([])
    lines = f.readlines()
    f.close()
    for line in lines:
        line = line.lower()
        if line.find(';') != -1:
            line = line[:line.find(';')]
        line = line.strip(' \t\r\n')
        if len(line):
            setW.add(line)
    return setW


def boundary_split(s, removePunctuation = True):
    if removePunctuation:
        p = re.compile('[\.,!?()\[\]{}:;"\'<>/ \n\r\t]')
        return [el for el in p.split(s) if el]
    else:
        t = []
        s = re.split('\s', s)
        p = re.compile('(\W)')
        for phrase in s:
            words = p.split(phrase)
            for word in words:
                t.append(word)
        return [el for el in t if el]

class Preprocess(object):

    def __init__(self, language=None, inputEncoding='utf-8', outputEncoding='utf-8', normType = 'lemmatize'):
        language = language or 'en'
        self.inputEncoding = inputEncoding
        self.outputEncoding = outputEncoding
        self.tokenize = boundary_split
        self.removedWords = []
        if normType == 'stem' and len(self.langData[language]) == 3:
            self.lemmatizer, self.stopwords = (self.langData[language][2], self.langData[language][1])
        else:
            self.lemmatizer, self.stopwords = self.langData[language][:2]

    def _in2utf(self, s):
       return s.decode(self.inputEncoding, 'replace').encode('utf-8', 'ignore')

    def _utf2out(self, s):
       return s.decode('utf-8', 'ignore').encode(self.outputEncoding, 'ignore')
        
    def doOnExampleTable(self, data, textAttribute=None, meth=None, callback=None):
        newData = orange.ExampleTable(data)
        textAttributePos = getTextAttributePos(data, textAttribute)
        for ex in newData:
            ex[textAttributePos] = meth(ex[textAttributePos].value)
            if callback:
                callback()
        return newData
        
    def lemmatizeExampleTable(self, data, textAttribute, callback = None):
        return self.doOnExampleTable(data, textAttribute, self.lemmatize, callback)
        
    def lemmatize(self, token):
        if isinstance(token, types.StringTypes):
            return self._utf2out(self.lemmatizer(self._in2utf(token)))
        elif isinstance(token, types.ListType):
            return [self._utf2out(self.lemmatizer(self._in2utf(t))) for t in token]
        else:
            raise TypeError

    def lowercaseExampleTable(self, data, textAttribute=None, callback=None):
        """return a data set whith a text of a text attribute in lowercase"""
        textAttributePos = getTextAttributePos(data, textAttribute)
        return self.doOnExampleTable(data, textAttributePos, self.lowercase, callback)

    def lowercase(self, text, textAttribute=None):
        """return a string in lowercase"""
        text = text.decode(self.inputEncoding, "ignore")
        return text.lower().encode(self.inputEncoding)


    def removeStopwordsFromExampleTable(self, data, textAttribute=None, callback = None):
        textAttributePos = getTextAttributePos(data, textAttribute)
        return self.doOnExampleTable(data, textAttributePos, self.removeStopwords, callback)
    
    def removeStopwords(self, text):
        if isinstance(text, types.StringTypes):
            tokens = self.tokenize(text)
            tokens = [token for token in tokens if self.lowercase(token) not in self.stopwords]
            text = ' '.join(tokens)
            return text
            #return self._utf2out(tmt.removeWords(self._in2utf(text), list(self.stopwords)))
        elif isinstance(text, types.ListType):
            return [t for t in text if self.lowercase(t) not in self.stopwords] or None
            #return [self._utf2out(t) for t in text if t not in self.stopwords] or None
        else:
            raise TypeError

    def removeWordsFromExampleTable(self, data, textAttribute=None, callback = None):
        textAttributePos = getTextAttributePos(data, textAttribute)
        return self.doOnExampleTable(data, textAttributePos, self.removeWords, callback)
   
    # function filters text for words in removeWords
    def removeWords(self, text):
        if isinstance(text, types.StringTypes):
            tokens = self.tokenize(text)
            tokens = [token for token in tokens if (self.lowercase(token) not in self.removedWords and len(token) > 2)]
            text = ' '.join(tokens)
            return text
        elif isinstance(text, types.ListType):
            return [t for t in text if (self.lowercase(t) not in self.removedWords and len(t) > 2)] or None
        else:
            raise TypeError        

    import textConfiguration
    __languageDataPath = textConfiguration.datasetsPath
    langData = {
#            'en' : (lambda x: x, [], lambda x: re.split(r'\b', x, re.DOTALL)),
            'en' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-en.bin')).lemmatizeText,
                    loadWordSet(os.path.join(__languageDataPath,'stopwords_en.txt')),
                    orngTextWrapper.porter().lemmatizeText),
            'hr' : (orngTextWrapper.lemmatizer(os.path.join(__languageDataPath,'lem-hr.fsa')).lemmatizeText,
                    loadWordSet(os.path.join(__languageDataPath,'stopwords_hr.txt'))),
            'fr' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-fr.bin')).lemmatizeText,
                    loadWordSet(os.path.join(__languageDataPath,'stopwords_fr.txt'))),
            'bg' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-bg.bin')).lemmatizeText, set()),
            'cs' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-cs.bin')).lemmatizeText, set()),
            'et' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-et.bin')).lemmatizeText, set()),
            'ge' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-ge.bin')).lemmatizeText, set()),
            'hu' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-hu.bin')).lemmatizeText, set()),
            'it' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-it.bin')).lemmatizeText, set()),
            'ro' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-ro.bin')).lemmatizeText, set()),
            'sl' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-sl.bin')).lemmatizeText, set()),
            'es' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-es.bin')).lemmatizeText, set()),
            'sr' : (orngTextWrapper.lemmagen(os.path.join(__languageDataPath,'lem-sr.bin')).lemmatizeText, set()),
            }

def loadReuters(dirName):
    """Load all .sgm files from the directory dirName."""
    from xml.sax import make_parser, handler   
    import os, copy 

    cat = orange.StringVariable("category")
    name = orange.StringVariable("name")
    meta = orange.StringVariable("text")
    lewis = orange.StringVariable("lewissplit")
    date = orange.StringVariable("date")
    topics = orange.StringVariable("topics")
    addCat = [cat, name, meta, lewis, date, topics]
    dom = orange.Domain(addCat, 0)

    data = orange.ExampleTable(dom)
    cat = orange.StringVariable("category")
    name = orange.StringVariable("name")
    meta = orange.StringVariable("text")
    lewis = orange.StringVariable("lewissplit")
    date = orange.StringVariable("date")
    topics = orange.StringVariable("topics")
    addCat = [cat, name, meta, lewis, date, topics]
    dom = orange.Domain(addCat, 0)

    data = orange.ExampleTable(dom)


    class ReutersHandler(handler.ContentHandler):
        def __init__(self):
            self.chars = []
            self.parse = True                        
            self.ignoreTags = set(['places','people','orgs','exchanges','companies','unknown'])
            self.normalTags = set(['date','topics','title','dateline','body','text'])
            self.document = {'dateline':'','title':'','body':''}
            self.f = None
            self.ex = orange.Example(dom)
                        
        def startElement(self, name, attrs):
            if name.lower() == 'reuters':
                for attName in attrs.keys():
                    if attName.lower() == 'newid':
                        self.ex['name'] = attrs.getValue(attName).encode('utf8','ignore')
                    elif attName.lower() == 'topics':
                       self.ex['topics'] = attrs[attName].encode('utf8','ignore')
                    elif attName.lower() == 'lewissplit':
                       self.ex['lewissplit'] = attrs.getValue(attName).encode('utf8','ignore')
            elif name.lower() in self.ignoreTags:
                self.parse = False
            elif name.lower() in self.normalTags:
                self.parse = True
            else:
                pass

        def endElement(self, name):
            if name.lower() in self.ignoreTags:
                self.parse = True
            elif name.lower() in self.normalTags:
                if name.lower() == 'date':
                   self.ex['date'] = ' '.join(self.chars).encode('utf8','ignore')
                elif name.lower() == 'topics':
                   for i in self.chars:
                      if i in set(['',' ','\n','\r','\t']):
                         self.chars.remove(i)
                   self.ex['category']= '+'.join(self.chars).encode('utf8','ignore')
                self.document[name.lower()] = ' '.join(self.chars).encode('utf8','ignore')
                self.chars = []
            elif name.lower() == 'reuters':
                self.ex['text'] = self.document['title'] + '\n' + self.document['dateline'] + '\n' + self.document['body']
                data.append(self.ex)
                self.ex = orange.Example(dom)
                self.chars = []
            else:
                pass


        def characters(self, chrs):
            if self.parse:
                self.chars.append(chrs)

    files = os.listdir(dirName)
    files.sort()
    for fileName in files:
      fileName = os.path.join(dirName, fileName)
      if fileName[-4:] == '.sgm':
          p = make_parser()
          p.setContentHandler(ReutersHandler())
          f = open(fileName)
          forbidden = set(['&#5;','&#22;','&#1;','&#31;','&#2;','&#3;','&#27;[B','&#30;','&#127;','\xFC'])
          tmp = '_tmpsgmFile'
          g = open(tmp, 'w')
          g.write('<?xml version=\"1.0\" ?>\n')
          g.write('<docset>')
          f.readline()
          for line in f:
              for c in forbidden:
                  line = line.replace(c, '')
              g.write(line)
          f.close()
          g.write('</docset>')
          g.close()
          f = open(tmp)
          try:
             p.parse(f)
          except:
             print 'Error loading file %s\n' % fileName
          f.close()
          os.remove(tmp)         

    return data

def loadFromXML(fileName, tags={}, doNotParse=[]):
    """returns ExampleTable, as already implemented by Mladen"""
    cat = orange.StringVariable("category")
    sel = orange.StringVariable("selection")
    name = orange.StringVariable("name")
    meta = orange.StringVariable("text")
    addCat = [cat, sel, name, meta]
    dom = orange.Domain(addCat, 0)    
    data = orange.ExampleTable(dom)
    
    f = open(fileName, "r")
    t = DocumentSetRetriever(f, tags = tags, doNotParse = doNotParse)
    
    while 1:
        # load document
        ex = orange.Example(dom)
        doc = t.getNextDocument()
        
        if not len(doc): break
        ex['category'] = ".".join([d.strip().encode('utf-8','ignore') for d in doc['categories']])
        ex['selection'] = ''
        ex['name'] = " ".join([("%s" % meta[1]).encode('utf-8','ignore') for meta in doc['meta']])
        ex['text'] = doc['content'].strip().encode('utf-8','ignore')
        
        
        data.append(ex)
    return data
        
def loadFromListWithCategories(fileName):
    """
    File has two lines for each document:
       *  first line contains the path to the document
       *  second line contains space separated categories
    
    ExampleTable is returned whose domain contains category, name and text
    """
    cat = orange.StringVariable("category")
    name = orange.StringVariable("name")
    meta = orange.StringVariable("text")
    addCat = [cat, name, meta]
    dom = orange.Domain(addCat, 0)    
    data = orange.ExampleTable(dom)
    
    
    f = open(fileName)
    while 1:
        path = f.readline().strip()
        if not path: break
        categories = f.readline().strip().split(" ")
        
        tmpFile = open(path)
               
        ex = orange.Example(dom)
        ex["name"] = path
        ex["category"] = ".".join(categories)
        ex["text"] = "".join(tmpFile.readlines())
        data.append(ex) 
            
    f.close()
    return data

def bagOfWords(exampleTable, preprocessor=None, textAttribute=None, stopwords=None, callback=None):
    """given the data return a bag-of-words representation for one of its string attributes"""
    p = preprocessor
    domaincopy = orange.Domain(exampleTable.domain)
    # create new ExampleTable
    data = orange.ExampleTable(exampleTable)
    textAttributePos = getTextAttributePos(data, textAttribute)
    #data.domain = orange.Domain(exampleTable.domain)

    # for ex in exampleTable:
    #       kreiraj newEx koji ima attribut category i name
    #       tokeniziraj ex["text"]
    #       svaki token koji nije interpunkcija dodaj u newex kao metaattribut koristeci incFreqWord
    #       dodaj newex u newexampletable

    allWords = {}
    for ex in data:
        if not preprocessor:
           if stopwords:
              tokens = boundary_split(ex[textAttributePos].value.decode('utf-8','ignore').encode('cp1250','ignore'))
              tokens = [w for w in tokens if w.lower() not in stopwords]
           else:
              tokens = boundary_split(ex[textAttributePos].value.decode('utf-8','ignore').encode('cp1250','ignore'))
        else:
            tokens = preprocessor.removeStopwords(preprocessor.tokenize(preprocessor.lemmatize(preprocessor.lowercase(ex[textAttributePos].value))))
        wordList = dict.fromkeys(tokens, 0)
        for token in tokens:
            wordList[token] += 1.0

        for k in wordList.keys():
           id = allWords.get(k, 0)
           if not id:
              id = orange.newmetaid()
              allWords[k] = id
           ex[id] = wordList[k]
        if callback:
            callback()

    data.domain.addmetas(dict([(id, orange.FloatVariable(k)) for k, id in allWords.items()]), TEXTMETAID)

    #exampleTable.domain = orange.Domain(data.domain.attributes)
    exampleTable.changeDomain(domaincopy)
    # vrati newexampletable
    return data

#selectFeaturesByFrequency(bof, min=1, max=None)
#selectFeaturesByChiSquare(bof, min=4.0)


#########data = loadFromListWithCategories('list.txt')
#p = Preprocess()
################print p.tokenize(data[0]['text'].value)
######################bow = bagOfWords(data)

############################################
##
## Parse document
## It could be better to use exsting lib for parsing XML (Beautiful Soup)

class DocumentSetHandler(handler.ContentHandler):            
    def __init__(self, tags = None, doNotParse = []):
        self.tagsToHandle = ["content", "category", "document", "categories"]
        # set default XML tags
        self.name2tag = {}
        if not tags:
            self.tags = {}
            for tag in self.tagsToHandle:
                self.tags[tag] = tag
                self.name2tag[tag] = tag
        else:
            self.tags = {}
            for tag in self.tagsToHandle:
                if not tags.has_key(tag):
                    self.tags[tag] = tag
                    self.name2tag[tag] = tag
                else:
                    self.tags[tag] = tags[tag]
                    self.name2tag[tags[tag]] = tag
            

                
            
        # for current document being parsed
        self.curDoc = {}
        self.documents = []
        self.level = []
            
        # other settings
        self.doNotParse = doNotParse[:]
        self.doNotParseFlag = 0
    def startElement(self, name, attrs):
        if self.name2tag.has_key(name):
            name = self.name2tag[name]
##        if name == "document": 
##            globals()['countdoc'] =globals()['countdoc'] + 1
        if name in self.doNotParse:
            self.doNotParseFlag += 1
        else:
            try:
                func = getattr(self, 'do' + name.capitalize())
                self.level.append(name)
                func(attrs)
            except:
                if name in self.tags:
                    self.level.append(name)
                    self.curDoc[name] = []
    def endElement(self, name):
        if self.name2tag.has_key(name):
            name = self.name2tag[name]        
        if name in self.tags:
            self.level.pop()
            if name == "document":
                self.curDoc["category"] = []
                self.curDoc["content"] = "".join(self.curDoc["content"])
                self.documents.append(self.curDoc)
                self.curDoc = {}
            elif name == "category":
                self.curDoc["categories"].append("".join(self.curDoc["category"]))
            elif name != "categories":
                self.curDoc[name] = "".join(self.curDoc[name])
        elif name in self.doNotParse:
            self.doNotParseFlag -= 1
    def characters(self, chrs):
        if not self.doNotParseFlag:
            try:
                # check in which tag are the characters
                # only tagsToHandle are parsed, others will raise exception that is ignored
                name = self.level[-1]
                if name not in ["document", "categories"]:
                    self.curDoc[name].append(chrs)
            except:
                pass
    def doDocument(self, attrs):
        self.curDoc["meta"] = attrs.items()[:]
        self.curDoc["content"] = []
        self.curDoc["category"] = []
        self.curDoc["categories"] = [] 
    def doContent(self, attrs):
        self.curDoc["content"] = []
    def doCategory(self, attrs):
        self.curDoc["category"] = []
    def doCategories(self, attrs):
        self.curDoc["categories"] = []

class DocumentSetRetriever:

    def __init__(self, source, tags = None, doNotParse = []):
        self.source = source
        self.handler = DocumentSetHandler(tags, doNotParse)
        self.parser = make_parser()
        self.parser.reset()
        self.parser.setContentHandler(self.handler)

    def getNextDocument(self):
        while 1:
            if len(self.handler.documents):
                curDoc = self.handler.documents.pop(0)
                return curDoc
            if self.source.closed:
                return {}
            chunk = self.source.read(10000)
            if not chunk:
                self.parser.close()
                return {}
            else:
                self.parser.feed(chunk)

def saveExampleTable(table, fileName):
   from pickle import dump

   f = open(fileName, 'w')
   dump(table, f)
   f.close()

def loadExampleTable(fileName):
   from pickle import load

   f = open(fileName)
   table = load(f)
   f.close()
   return table

class Preprocessor_norm:
   def __call__(self, data, LNorm = 2, callback = None):
      """Normalizes the ExampleTable table using the given L-Norm. The default norm is L2."""
      from math import sqrt
      newtable = orange.ExampleTable(data)
      if LNorm == 2:
         for example in newtable:
            sum = 0         
            for v in example.getmetas(TEXTMETAID).values():
               #val = example[word].value
               sum += v*v
            sum = sqrt(sum)
            for word in example.getmetas(TEXTMETAID).keys():
               example[word] = example[word] / sum
            if callback: callback()
         return newtable
      elif LNorm == 1:
         for example in newtable:
            sum = 0         
            for v in example.getmetas(TEXTMETAID).values():
               #val = example[word].value
               sum += v
            for word in example.getmetas(TEXTMETAID).keys():
               example[word] = example[word] / sum
            if callback: callback()
         return newtable      
      elif LNorm > 2:
         from math import pow
         for example in newtable:
            sum = 0         
            for v in example.getmetas(TEXTMETAID).values():
               #val = example[word].value
               sum += pow(v, LNorm)
            sum = pow(sum, 1 / LNorm)
            for word in example.getmetas(TEXTMETAID).keys():
               example[word] = example[word] / sum
            if callback: callback()
         return newtable
      elif LNorm == 0:
         for example in newtable:
            sum = 0         
            for v in example.getmetas(TEXTMETAID).values():
                  #val = example[word].value
                  if v > sum:
                     sum = v
            for word in example.getmetas(TEXTMETAID).keys():
               example[word] = example[word] / sum
            if callback: callback()
         return newtable
      #return data
      
import math

class Preprocessor_tfidf:
    def __init__(self, termNormalizers):
        self.termNormalizers = termNormalizers

    def __call__(self, data, callback = None):
        if type(data) == orange.ExampleTable:
            newData = orange.ExampleTable(data)
            for ex in newData:
                for id, val in ex.getmetas(TEXTMETAID).items():
                    ex[id] *= self.termNormalizers.get(id, 0)
                if callback: callback()
            return newData
        else:
            ex = orange.Example(data)
            for id, val in ex.getmetas(TEXTMETAID).items():
                ex[id] *= self.termNormalizers.get(id, 0)
            return ex


class PreprocessorConstructor_tfidf:
    def __call__(self, data):
        frequencies = {}
        for ex in data:
            for id in ex.getmetas(TEXTMETAID):
                frequencies[id] = frequencies.get(id, 0) + 1

        N = float(len(data))
        normalizers = dict([(id, math.log(N/f)) for id, f in frequencies.items()])
        return Preprocessor_tfidf(normalizers)


def cos(bow, normalize = True, distance = 0, callback = None, metaClass=TEXTMETAID):
   """returns distance matrix for bag-of-words measured as cosine of a angle btw feature vectors"""
   from math import sqrt
   c = orange.SymMatrix(len(bow))
   metas = {}
   for i, ex in enumerate(bow):
      metas[i] = ex.getmetas(metaClass)
   for i, ex1 in enumerate(bow):
      for j in range(i):
         if not distance:
            c[i, j] = float(sum([v1 * metas[j].get(id, 0) for id, v1 in metas[i].items()]))
         else:
            try:
               c[i, j] = 1. / float(sum([v1 * metas[j].get(id, 0) for id, v1 in metas[i].items()]))
            except:
               c[i, j] = 10000000
         if normalize and c[i, j]:
            c[i, j] /= sqrt(sum([k**2 for k in metas[j].values()])) * sqrt(sum([p**2 for p in metas[i].values()]))
         if callback: callback()
   return c

def FSMRandom(table, perc = True):
   from random import random
   words = {}
   for ex in table:
      for v in ex.getmetas(TEXTMETAID).values():
         varname = v.variable.name
         if not words.has_key(varname):
            words[varname] = random()
   t = [(k, v) for k, v in words.items()]
   if perc:
      t.sort(cmp = lambda x, y: cmp(x[1], y[1]), reverse = True)
   return t
 


def FSMTDF(table, perc = True):
   words = {}
   for ex in table:
      for v in ex.getmetas(TEXTMETAID).values():
         varname = v.variable.name
         if words.has_key(varname):
            words[varname] += 1.0
         else:
            words[varname] = 1.0
   t = [(k, v) for k, v in words.items()]
   if perc:
      t.sort(cmp = lambda x, y: cmp(x[1], y[1]), reverse = True)
   return t


def FSMTF(table, perc = True):
   words = {}
   #featureTotal = len(table.domain.getmetas(TEXTMETAID))
   #featNo = featureTotal * perc / 100
   for ex in table:
      for v in ex.getmetas(TEXTMETAID).values():
         varname = v.variable.name
         if words.has_key(varname):
            words[varname] += v.value
         else:
            words[varname] = v.value
   t = [(k, v) for k, v in words.items()]
   if perc:
      t.sort(cmp = lambda x, y: cmp(x[1], y[1]), reverse = True)
   return t
   #someList = [k for k, v in t] 
   #return set(someList[int(math.ceil(featNo)):])


def FSMMin(table, threshold, perc = True):
   """removes the features that occur less than a minimal threshold"""
   #gets a dictionary with examples already sorted by decreasing values
   #print 't %s ' % table
   if perc:
      featTotal = len(table)
      #number of features to remove
      featNo = int(math.ceil(featTotal * threshold))      
      return [i[0] for i in table[-featNo:]]
   
   else:
      return [i[0] for i in table if i[1] < threshold]
##      i = 0
##      while 1:
##         if table[i][1] < threshold or i == len(table) - 1:
##            break
##         i += 1
##      #feature has to have the value more than threshold to be kept
##      return [i[0] for i in table[i + 1:]]

def FSMMax(table, threshold, perc = True):
   """removes the features that occur more than a minimal threshold"""
   #gets a list of tuples with examples already sorted by decreasing values
   if perc:
      featTotal = len(table)
      #number of features to remove
      featNo = int(math.ceil(featTotal * threshold))
      return [i[0] for i in table[:featNo]]
   else:
      return [i[0] for i in table if i[1] > threshold]
##      i = len(table) - 1
##      while 1:
##         if table[i][1] > threshold or i == 0:
##            break
##         i -= 1
##      return [i[0] for i in table[:i + 1]]

def FSS(table, funcName, operator, threshold, perc = True, callback=None):
   import math
   if (funcName != "ANNIE") and perc and threshold > 1:
      threshold = threshold / 100.
      threshold = min(threshold, 1)
   operators = {'MAX': FSMMax, 'MIN': FSMMin}
   functions = {'TF': FSMTF, 'RAND': FSMRandom, 'TDF': FSMTDF}
   #each FSM function returs a set of metaattributes that need to be removed
   #newTable = orange.ExampleTable(table)
   #newTable.domain = orange.Domain(table.domain)
  
  
   # we use FSS which has Annie M. suggested
   # we order the left words by decreasing frequency (total number
   # of occurencies through all the texts) : this is the first list and
   # second we order the words by decreasing occurencies through texts , that
   # means that we count the number of texts in which the words appear : second list.
   # We keep  the first 1000 words in each list and take the intersection of
   # both. In general we have between 850 to 900 words left.

   if funcName == "ANNIE":
      featuresF = FSMTF(table,False)
      featuresF.sort(lambda x,y:cmp(y[1],x[1]))
      featuresF = [x for (x,y) in featuresF] # we take only names 
      featuresF = set(featuresF[0:threshold])
      featuresDF = FSMTDF(table,False)
      featuresDF.sort(lambda x,y:cmp(y[1],x[1]))
      featuresDF = [x for (x,y) in featuresDF] # only names
      featuresDF = set(featuresDF[0:threshold])
      featurestokeep = featuresDF.intersection(featuresF)   # we use a intersection between two lists of terms
      allfeatures = set([i.name for i in table.domain.getmetas(TEXTMETAID).values()])
      removeList = list(allfeatures.difference(featurestokeep))
   else:
      removeList = operators[operator](functions[funcName](table, perc), threshold, perc)

   remMetas = set([])
##   for k in removeList:
##      met = table.domain.metaid(k)
##      #newTable.removeMetaAttribute(met)
##      #[ex.removemeta(k) for ex in newTable if ex.hasmeta(k)]
##      remMetas.add(met)
   remMetas = set(removeList)
   #a = set(table.domain.getmetas(TEXTMETAID))
   a = set([i.name for i in table.domain.getmetas(TEXTMETAID).values()])
   #a = set([i.name for i in table.domain.getmetas(TEXTMETAID, str).values()])
   metas = a.difference(remMetas)
   #domaincopy = orange.Domain(table.domain.attributes, False) 
   #newTable = orange.ExampleTable(orange.Domain(domaincopy))

   metadict = dict([(table.domain.metaid(i), orange.FloatVariable(i)) for i in metas])
   if callback: callback()
   #m2 = dict([(v.name, k) for k, v in metadict.items()])
##   for ex in table:
##      newex = orange.Example(domaincopy)
##      for att in newex.domain:
##         newex[att] = ex[att]
##      for k in ex.getmetas(TEXTMETAID).keys():
##         if k in metadict.keys():
##            newex[k] = ex[k]
##      newTable.append(newex)

##   newTable = orange.ExampleTable(orange.Domain(table.domain.attributes), table)
##   newkeys = {}
##   for ex in table:
##      for k in ex.getmetas(TEXTMETAID).keys():
##         if k in metadict.keys():
##            id = newkeys.get(metadict[k].name, 0)
##            if not id:
##               id = orange.newmetaid()
##               newkeys[metadict[k].name] = id
##            newex[id] = ex[k]
##      newTable.append(newex)
##   #newTable.domain.addmetas(metadict)
##   newTable.domain.addmetas(dict([(id, orange.FloatVariable(k)) for k, id in newkeys.items()]), True)

   newTable = orange.ExampleTable(orange.Domain(table.domain), table)
   newTable.domain.removemeta(removeList)
   for ex in newTable:
      #for k, v in ex.getmetas(TEXTMETAID).items(): the problem is because SVM gets all metas and thus FSS does not nave any influence, probably there is a bug in a removemeta method
      for k, v in ex.getmetas().items():
         if not v.variable:
            ex.removemeta(k)
   return newTable


def DSMNF(table, threshold, max):
    #number of features, removes documents according to a number
    #of different features it has
    removeList = []
    for ex in table:
        features = len(ex.getmetas(TEXTMETAID))
        if max and features > threshold:
            removeList.append(0)
        elif not max and features < threshold:
            removeList.append(0)
        else:
            removeList.append(1)
    return removeList
        


def DSMWF(table, threshold, max):
   """word frequency, removes documents according to the total number of words
   """
   removeList = []
   for ex in table:
      words = 0
      for freq in ex.getmetas(TEXTMETAID).values():
         words += freq
      if max and words > threshold:
         removeList.append(0)
      elif not max and words < threshold:
         removeList.append(0)
      else:
         removeList.append(1)
   return removeList



def DSS(table, funcName, operator, threshold, callback=None):
   """Document subset selection. Takes a function name and an operator and
    removes the documents with the desired measure below (or above) the threshold.
   """
   import math
   functions = {'WF': DSMWF, 'NF': DSMNF}
   newTable = orange.ExampleTable(table)
   operators = {'MAX': True, 'MIN': False}

   #removelist is a list of indices of examples that need to be removed(zeroes indicate that an example is to be removed)
   removeList = functions[funcName](table, threshold, operators[operator])

   removed = newTable.select(removeList, negate=1)
   newTable = newTable.select(removeList)
   removedMetas = set([])
   for ex in removed:
        for k in ex.getmetas(TEXTMETAID).keys():
            removedMetas.add(k)
        
   if callback: callback()
   for ex in newTable:
        for k, v in ex.getmetas(TEXTMETAID).items():
            if k in removedMetas:
                removedMetas.remove(k)

   for k in removedMetas:
        newTable.domain.removemeta(k)
   return newTable

   

def extractLetterNGram(table, n=2, callback=None, textAttribute=None):
   """returns a data set with a  letter ngram features from a selected text attribute
   n is the window size (size of ngrams)"""

   textAttributePos = getTextAttributePos(table, textAttribute)
   domaincopy = orange.Domain(table.domain)
   newTable = orange.ExampleTable(table)
   #newTable.domain = orange.Domain(table.domain)

   ngramsSet = set([])
   allngrams = {}
   for ex in newTable:
      text = ex[textAttributePos].value
      i = 0
      ngrams = {}
      while i < len(text) - n + 1:
         ng = text[i:i+n]
         ngrams[ng] = ngrams.get(ng, 0) + 1.0
         i += 1
         
      #exdomain = ex.domain
      for k in ngrams.keys():
         id = allngrams.get(k, 0)
         if not id:
            id = orange.newmetaid()
            allngrams[k] = id
         ex[id] = ngrams[k]
      if callback: callback()

   newTable.domain.addmetas(dict([(id, orange.FloatVariable(k)) for k, id in allngrams.items()]), TEXTMETAID)
   #table.domain = orange.Domain(domaincopy)
   table.changeDomain(domaincopy)
   #table.domain.removemeta(table.domain.getmetas(TEXTMETAID).keys())
   return newTable




def extractWordNGram(table, preprocessor = None, n = 2, stopwords = None, threshold = 4, measure = 'FREQ'):
   """Builds the word ngram features."""
   import re
   domaincopy = orange.Domain(table.domain)
   newTable = orange.ExampleTable(table)
   seps = '.,!?()[]{}:; \n\r\t"\''
   notAllowed = ''
##   separators = set(seps)
   p = re.compile('[\.,!?(){}:;]')
   ps = re.compile('[ \n\r\t"]')
   na = re.compile('\\W')

############################################################################################################
##                                        DIGRAMS                                                         ##
############################################################################################################
   if n == 2:
      wordfreqs = {}
      digramfreqs = {}
      digrams = {}
      
      for ex in newTable:
         if not preprocessor:
            phrases = p.split(ex['text'].value.decode('utf-8','ignore').encode('cp1250','ignore'))
         else:
            phrases = preprocessor.removeStopwords(preprocessor.tokenize(preprocessor.lemmatize(preprocessor.lowercase(ex['text'].value))))
         #sad imam tokene, makni prazne stringove
         phrases = [i for i in phrases if i]
         for phrase in phrases:
             i = 0
             tokens = ps.split(phrase)
             tokens = [tok for tok in tokens if tok]
             if not tokens: continue
             while i < len(tokens) - 1:
                wordfreqs[tokens[i]] = wordfreqs.get(tokens[i], 0) + 1.0
                if stopwords:
                   if tokens[i].lower() in stopwords or tokens[i+1].lower() in stopwords or tokens[i].isdigit() or tokens[i+1].isdigit() or na.search(tokens[i]) or na.search(tokens[i+1]):
                      i += 1
                      continue
                digramfreqs[tokens[i] + ' ' + tokens[i+1]] = digramfreqs.get(tokens[i] + ' ' + tokens[i+1], 0) + 1.0
                i += 1
             #don't forget to count the last word
             wordfreqs[tokens[i]] = wordfreqs.get(tokens[i], 0) + 1.0

      #now we have all the needed information to comptue statistics and filter them (using threshold)
      digramFeatures = set([]) #this set contains the digrams that will be added as features
      N = sum(digramfreqs.values())
      M = sum(wordfreqs.values())
      if measure == 'FREQ':
         for k, v in digramfreqs.items():
            if v >= threshold:
               digramFeatures.add(k)
      elif measure == 'MI':
         from math import log
         for k, v in digramfreqs.items():
            mi = log((v * v * M * M) / (wordfreqs[k.split(' ')[0]] * wordfreqs[k.split(' ')[1]] * N), 2.)
            if mi >= threshold:
               digramFeatures.add(k)
      elif measure == 'DICE':
         for k, v in digramfreqs.items():
            dice = (2 * v) / (wordfreqs[k.split(' ')[0]] + wordfreqs[k.split(' ')[1]])
            if dice >= threshold:
               digramFeatures.add(k)
      elif measure == 'CHI':
##         N = sum(digramfreqs.values())
##         M = sum(wordfreqs.values())
         for k, v in digramfreqs.items():
            o11 = v
            o01 = wordfreqs[k.split(' ')[1]] - v + 1e-307
            o10 = wordfreqs[k.split(' ')[0]] - v + 1e-307
            o00 = N - v
            pa = wordfreqs[k.split(' ')[0]] / M
            pb = wordfreqs[k.split(' ')[1]] / M
            e11 = pa * pb * N
            e01 = (1 - pa) * pb * N
            e10 = pa * (1 - pb) * N
            e00 = (1 - pa) * (1 - pb) * N
            chi1 = ((e11 - o11) ** 2) / e11
            chi2 = ((e10 - o10) ** 2) / e10
            chi3 = ((e01 - o01) ** 2) / e01
            chi4 = ((e00 - o00) ** 2) / e00
            chi = chi1 + chi2 + chi3 + chi4
            if chi >= threshold:
               digramFeatures.add(k)
      elif measure == 'LL':
         from math import log
##         N = sum(digramfreqs.values())
##         M = sum(wordfreqs.values())
         for k, v in digramfreqs.items():
            o11 = v
            o01 = wordfreqs[k.split(' ')[1]] - v + 1e-307
            o10 = wordfreqs[k.split(' ')[0]] - v + 1e-307
            o00 = N - v
            pa = wordfreqs[k.split(' ')[0]] / M
            pb = wordfreqs[k.split(' ')[1]] / M
            e11 = pa * pb * N
            e01 = (1 - pa) * pb * N
            e10 = pa * (1 - pb) * N
            e00 = (1 - pa) * (1 - pb) * N
            log1 = o11 * (log(o11, 10) - log(e11, 10))
            log2 = o10 * (log(o10, 10) - log(e10, 10))
            log3 = o01 * (log(o01, 10) - log(e01, 10))
            log4 = o00 * (log(o00, 10) - log(e00, 10))
            ll = log1 + log2 + log3 + log4
            if ll >= threshold:
               digramFeatures.add(k)
               
      #finally, add the features         
      for ex in newTable:
         if not preprocessor:
            phrases = p.split(ex['text'].value.decode('utf-8','ignore').encode('cp1250','ignore'))
         else:
            phrases = preprocessor.removeStopwords(preprocessor.tokenize(preprocessor.lemmatize(preprocessor.lowercase(ex['text'].value))))
         #sad imam tokene, makni prazne stringove
         phrases = [i for i in phrases if i]
         localdigrams = {}
         for phrase in phrases:
             i = 0
             tokens = ps.split(phrase)
             tokens = [tok for tok in tokens if tok]
             while i < len(tokens) - 1:
                if tokens[i] + ' ' + tokens[i+1] in digramFeatures:
                   localdigrams[tokens[i] + ' ' + tokens[i+1]] = localdigrams.get(tokens[i] + ' ' + tokens[i+1], 0) + 1.0
                i += 1
                
         for k in localdigrams.keys():
            id = digrams.get(k, 0)
            if not id:
               id = orange.newmetaid()
               digrams[k] = id
            ex[id] = localdigrams[k]

      newTable.domain.addmetas(dict([(id, orange.FloatVariable(k)) for k, id in digrams.items()]), TEXTMETAID)

############################################################################################################
##                                        TRIGRAMS                                                        ##
############################################################################################################
   elif n == 3:
      wordfreqs = {}
      digramfreqs = {}
      trigramfreqs = {}
      trigrams = {}
      
      for ex in newTable:
         if not preprocessor:
            phrases = p.split(ex['text'].value.decode('utf-8','ignore').encode('cp1250','ignore'))
         else:
            phrases = preprocessor.removeStopwords(preprocessor.tokenize(preprocessor.lemmatize(preprocessor.lowercase(ex['text'].value))))
         #sad imam tokene, makni prazne stringove
         phrases = [i for i in phrases if i]
         for phrase in phrases:
             i = 0
             tokens = ps.split(phrase)
             tokens = [tok for tok in tokens if tok]
             if not tokens: continue
             while i < len(tokens) - 2:
                wordfreqs[tokens[i]] = wordfreqs.get(tokens[i], 0) + 1.0
                digramfreqs[tokens[i] + ' ' + tokens[i+1]] = digramfreqs.get(tokens[i] + ' ' + tokens[i+1], 0) + 1.0
                if stopwords:
                   if tokens[i].lower() in stopwords or tokens[i+2].lower() in stopwords or tokens[i].isdigit() or tokens[i+2].isdigit() or na.search(tokens[i]) or na.search(tokens[i+2]):
                      i += 1
                      continue
                trigramfreqs[tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2]] = trigramfreqs.get(tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2], 0) + 1.0
                i += 1
             #don't forget to count the last words
             if len(tokens) >= 1:
                wordfreqs[tokens[i]] = wordfreqs.get(tokens[i], 0) + 1.0
                if len(tokens)>=2:
                     wordfreqs[tokens[i+1]] = wordfreqs.get(tokens[i+1], 0) + 1.0
                     digramfreqs[tokens[i] + ' ' + tokens[i+1]] = digramfreqs.get(tokens[i] + ' ' + tokens[i+1], 0) + 1.0

      trigramFeatures = set([]) #this set contains the trigrams that will be added as features
      N = sum(trigramfreqs.values())
      M = sum(wordfreqs.values())
      if measure == 'FREQ':
         for k, v in trigramfreqs.items():
            if v >= threshold:
               trigramFeatures.add(k)
      elif measure == 'MI':
##         N = len(trigramfreqs)
##         M = len(wordfreqs)
         from math import log
         for k, v in trigramfreqs.items():
            mi = log((v * M * M * M) / (wordfreqs[k.split(' ')[0]] * wordfreqs[k.split(' ')[1]] * wordfreqs[k.split(' ')[2]] * N), 2.)
            if mi >= threshold:
               trigramFeatures.add(k)
      elif measure == 'H':
         if not stopwords:
            return table
         from math import log
##         N = len(trigramfreqs)
         for k, v in trigramfreqs.items():
            if wordfreqs[k.split(' ')[1]] in stopwords:
               h = 2 * log((v * N) / (wordfreqs[k.split(' ')[0]] * wordfreqs[k.split(' ')[2]]), 2.)
            else:
               h = log((v * N * N) / (wordfreqs[k.split(' ')[0]] * wordfreqs[k.split(' ')[1]] * wordfreqs[k.split(' ')[2]]), 2.)
            if h >= threshold:
               trigramFeatures.add(k)
      elif measure == 'DICE':
         for k, v in trigramfreqs.items():
            dice = (3 * v) / (wordfreqs[k.split(' ')[0]] + wordfreqs[k.split(' ')[1]] + wordfreqs[k.split(' ')[2]])
            if dice >= threshold:
               trigramFeatures.add(k)
      elif measure == 'CHI':
##         N = sum(trigramfreqs.values())
##         M = sum(wordfreqs.values())
         for k, v in trigramfreqs.items():
            splitList = k.split(' ')
            o000 = N - v
            o001 = wordfreqs[splitList[2]] - v + 1e-307
            o010 = wordfreqs[splitList[1]] - v + 1e-307
            o100 = wordfreqs[splitList[0]] - v + 1e-307
            o110 = digramfreqs[splitList[0] + ' ' + splitList[1]] - v + 1e-307
            o011 = digramfreqs[splitList[1] + ' ' + splitList[2]] - v + 1e-307
            o111 = v
            pa = wordfreqs[splitList[0]] / M
            pb = wordfreqs[splitList[1]] / M
            pc = wordfreqs[splitList[2]] / M
            e000 = (1 - pa) * (1 - pb) * (1 - pc) * N
            e001 = (1 - pa) * (1 - pb) * pc * N
            e010 = (1 - pa) * pb * (1 - pc) * N
            e100 = pa * (1 - pb) * (1 - pc) * N
            e110 = pa * pb * (1 - pc) * N
            e011 = (1 - pa) * pb * pc * N
            e111 = pa * pb * pc * N
            
            chi1 = ((e111 - o111) ** 2) / e111
            chi2 = ((e100 - o100) ** 2) / e100
            chi3 = ((e001 - o001) ** 2) / e001
            chi4 = ((e010 - o010) ** 2) / e010
            chi5 = ((e000 - o000) ** 2) / e000
            chi6 = ((e011 - o011) ** 2) / e011
            chi7 = ((e110 - o110) ** 2) / e110
            chi = chi1 + chi2 + chi3 + chi4 + chi5 + chi6 + chi7
            if chi >= threshold:
               trigramFeatures.add(k)
      elif measure == 'LL':
         from math import log
##         N = sum(trigramfreqs.values())
##         M = sum(wordfreqs.values())
         for k, v in trigramfreqs.items():
            splitList = k.split(' ')
            o000 = N - v
            o001 = wordfreqs[splitList[2]] - v + 1e-307
            o010 = wordfreqs[splitList[1]] - v + 1e-307
            o100 = wordfreqs[splitList[0]] - v + 1e-307
            o110 = digramfreqs[splitList[0] + ' ' + splitList[1]] - v + 1e-307
            o011 = digramfreqs[splitList[1] + ' ' + splitList[2]] - v + 1e-307
            o111 = v
            pa = wordfreqs[splitList[0]] / M
            pb = wordfreqs[splitList[1]] / M
            pc = wordfreqs[splitList[2]] / M
            e000 = (1 - pa) * (1 - pb) * (1 - pc) * N
            e001 = (1 - pa) * (1 - pb) * pc * N
            e010 = (1 - pa) * pb * (1 - pc) * N
            e100 = pa * (1 - pb) * (1 - pc) * N
            e110 = pa * pb * (1 - pc) * N
            e011 = (1 - pa) * pb * pc * N
            e111 = pa * pb * pc * N
            
            log1 = o111 * (log(o111, 10) - log(e111, 10))
            log2 = o110 * (log(o110, 10) - log(e110, 10))
            log3 = o011 * (log(o011, 10) - log(e011, 10))
            log4 = o001 * (log(o001, 10) - log(e001, 10))
            log5 = o100 * (log(o100, 10) - log(e100, 10))
            log6 = o010 * (log(o010, 10) - log(e010, 10))
            log7 = o000 * (log(o000, 10) - log(e000, 10))
            ll = log1 + log2 + log3 + log4 + log5 + log6 + log7
            if ll >= threshold:
               trigramFeatures.add(k)               
               
      #finally, add the features         
      for ex in newTable:
         if not preprocessor:
            phrases = p.split(ex['text'].value.decode('utf-8','ignore').encode('cp1250','ignore'))
         else:
            phrases = preprocessor.removeStopwords(preprocessor.tokenize(preprocessor.lemmatize(preprocessor.lowercase(ex['text'].value))))
         #sad imam tokene, makni prazne stringove
         phrases = [i for i in phrases if i]
         localtrigrams = {}
         for phrase in phrases:
             i = 0
             tokens = ps.split(phrase)
             tokens = [tok for tok in tokens]
             while i < len(tokens) - 2:
                if tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2] in trigramFeatures:
                   localtrigrams[tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2]] = localtrigrams.get(tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2], 0) + 1.0
                i += 1
            
         for k in localtrigrams.keys():
            id = trigrams.get(k, 0)
            if not id:
               id = orange.newmetaid()
               trigrams[k] = id
            ex[id] = localtrigrams[k]

      newTable.domain.addmetas(dict([(id, orange.FloatVariable(k)) for k, id in trigrams.items()]), TEXTMETAID)

############################################################################################################
##                                        TETRAGRAMS                                                      ##
############################################################################################################
      
   elif n == 4:
      wordfreqs = {}
      digramfreqs = {}
      trigramfreqs = {}
      tetragramfreqs = {}
      tetragrams = {}
      
      for ex in newTable:
         if not preprocessor:
            phrases = p.split(ex['text'].value.decode('utf-8','ignore').encode('cp1250','ignore'))
         else:
            phrases = preprocessor.removeStopwords(preprocessor.tokenize(preprocessor.lemmatize(preprocessor.lowercase(ex['text'].value))))
         #sad imam tokene, makni prazne stringove
         phrases = [i for i in phrases if i]
         for phrase in phrases:
             i = 0
             tokens = ps.split(phrase)
             tokens = [tok for tok in tokens if tok]
             if not tokens: continue
             while i < len(tokens) - 3:
                wordfreqs[tokens[i]] = wordfreqs.get(tokens[i], 0) + 1.0
                digramfreqs[tokens[i] + ' ' + tokens[i+1]] = digramfreqs.get(tokens[i] + ' ' + tokens[i+1], 0) + 1.0
                trigramfreqs[tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2]] = trigramfreqs.get(tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2], 0) + 1.0
                if stopwords:
                   if tokens[i].lower() in stopwords or tokens[i+3].lower() in stopwords or tokens[i].isdigit() or tokens[i+3].isdigit() or na.search(tokens[i]) or na.search(tokens[i+3]):
                      i += 1
                      continue
                tetragramfreqs[tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2] + ' ' + tokens[i+3]] = tetragramfreqs.get(tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2] + ' ' + tokens[i+3], 0) + 1.0
                i += 1
             #don't forget to count the last words
             lt = len(tokens)
             if lt >= 1:
                wordfreqs[tokens[i]] = wordfreqs.get(tokens[i], 0) + 1.0
                if lt >= 2:
                    wordfreqs[tokens[i+1]] = wordfreqs.get(tokens[i+1], 0) + 1.0
                    digramfreqs[tokens[i] + ' ' + tokens[i+1]] = digramfreqs.get(tokens[i] + ' ' + tokens[i+1], 0) + 1.0
                    if lt >= 3:
                        wordfreqs[tokens[i+2]] = wordfreqs.get(tokens[i+2], 0) + 1.0                
                        digramfreqs[tokens[i+1] + ' ' + tokens[i+2]] = digramfreqs.get(tokens[i+1] + ' ' + tokens[i+2], 0) + 1.0
                        trigramfreqs[tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2]] = trigramfreqs.get(tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2], 0) + 1.0

      tetragramFeatures = set([]) #this set contains the tetragrams that will be added as features
      N = sum(tetragramfreqs.values())
      M = sum(wordfreqs.values())
      if measure == 'FREQ':
         for k, v in tetragramfreqs.items():
            if v >= threshold:
               tetragramFeatures.add(k)
      elif measure == 'MI':
##         N = len(tetragramfreqs)
##         M = len(wordfreqs)
         from math import log
         for k, v in tetragramfreqs.items():
            mi = log((v * M * M * M * M) / (wordfreqs[k.split(' ')[0]] * wordfreqs[k.split(' ')[1]] * wordfreqs[k.split(' ')[2]] * wordfreqs[k.split(' ')[3]] * N), 2.)
            if mi >= threshold:
               tetragramFeatures.add(k)
      elif measure == 'DICE':
         for k, v in tetragramfreqs.items():
            dice = (4 * v) / (wordfreqs[k.split(' ')[0]] + wordfreqs[k.split(' ')[1]] + wordfreqs[k.split(' ')[2]] + wordfreqs[k.split(' ')[3]])
            if dice >= threshold:
               tetragramFeatures.add(k)
      elif measure == 'CHI':
##         N = len(tetragramfreqs)
##         M = len(wordfreqs)
         for k, v in tetragramfreqs.items():
            splitList = k.split(' ')
            o0000 = N - v
            o0001 = wordfreqs[splitList[3]] - v + 1e-307
            o0010 = wordfreqs[splitList[2]] - v + 1e-307
            o0100 = wordfreqs[splitList[1]] - v + 1e-307
            o1000 = wordfreqs[splitList[0]] - v + 1e-307
            o0011 = digramfreqs[splitList[2] + ' ' + splitList[3]] - v + 1e-307
            o0110 = digramfreqs[splitList[1] + ' ' + splitList[2]] - v + 1e-307
            o1100 = digramfreqs[splitList[0] + ' ' + splitList[1]] - v + 1e-307
            o0111 = trigramfreqs[splitList[1] + ' ' + splitList[2] + ' ' + splitList[3]] - v + 1e-307
            o1110 = trigramfreqs[splitList[0] + ' ' + splitList[1] + ' ' + splitList[2]] - v + 1e-307
            o1111 = v
            pa = splitList[0] / M
            pb = splitList[1] / M
            pc = splitList[2] / M
            pd = splitList[3] / M
            e0000 = (1 - pa) * (1 - pb) * (1 - pc) * (1 - pd) * N
            e0001 = (1 - pa) * (1 - pb) * (1 - pc) * pd * N
            e0010 = (1 - pa) * (1 - pb) * pc * (1 - pd) * N
            e0100 = (1 - pa) * pb * (1 - pc) * (1 - pd) * N
            e1000 = pa * (1 - pb) * (1 - pc) * (1 - pd) * N
            e0011 = (1 - pa) * (1 - pb) * pc * pd * N
            e0110 = (1 - pa) * pb * pc * (1 - pd) * N
            e1100 = pa * pb * (1 - pc) * (1 - pd) * N
            e0111 = (1 - pa) * pb * pc * pd * N
            e1110 = pa * pb * pc * (1 - pd) * N
            e1111 = pa * pb * pc * pd * N
            
            chi1 = ((e1111 - o1111) ** 2) / e1111
            chi2 = ((e0001 - o0001) ** 2) / e0001
            chi3 = ((e0010 - o0010) ** 2) / e0010
            chi4 = ((e0100 - o0100) ** 2) / e0100
            chi5 = ((e1000 - o1000) ** 2) / e1000
            chi6 = ((e0011 - o0011) ** 2) / e0011
            chi7 = ((e0110 - o0110) ** 2) / e0110
            chi8 = ((e1100 - o1100) ** 2) / e1100
            chi9 = ((e1110 - o1110) ** 2) / e1110
            chi10 = ((e0111 - o0111) ** 2) / e0111
            chi11 = ((e0000 - o0000) ** 2) / e0000
            chi = chi1 + chi2 + chi3 + chi4 + chi5 + chi6 + chi7 + chi8 + chi9 + chi10 + chi11
            if chi >= threshold:
               tetragramFeatures.add(k)
      elif measure == 'LL':
         from math import log
##         N = len(tetragramfreqs)
##         M = len(wordfreqs)
         for k, v in tetragramfreqs.items():
            splitList = k.split(' ')
            o0000 = N - v
            o0001 = wordfreqs[splitList[3]] - v + 1e-307
            o0010 = wordfreqs[splitList[2]] - v + 1e-307
            o0100 = wordfreqs[splitList[1]] - v + 1e-307
            o1000 = wordfreqs[splitList[0]] - v + 1e-307
            o0011 = digramfreqs[splitList[2] + ' ' + splitList[3]] - v + 1e-307
            o0110 = digramfreqs[splitList[1] + ' ' + splitList[2]] - v + 1e-307
            o1100 = digramfreqs[splitList[0] + ' ' + splitList[1]] - v + 1e-307
            o0111 = trigramfreqs[splitList[1] + ' ' + splitList[2] + ' ' + splitList[3]] - v + 1e-307
            o1110 = trigramfreqs[splitList[0] + ' ' + splitList[1] + ' ' + splitList[2]] - v + 1e-307
            o1111 = v
            pa = splitList[0] / M
            pb = splitList[1] / M
            pc = splitList[2] / M
            pd = splitList[3] / M
            e0000 = (1 - pa) * (1 - pb) * (1 - pc) * (1 - pd) * N
            e0001 = (1 - pa) * (1 - pb) * (1 - pc) * pd * N
            e0010 = (1 - pa) * (1 - pb) * pc * (1 - pd) * N
            e0100 = (1 - pa) * pb * (1 - pc) * (1 - pd) * N
            e1000 = pa * (1 - pb) * (1 - pc) * (1 - pd) * N
            e0011 = (1 - pa) * (1 - pb) * pc * pd * N
            e0110 = (1 - pa) * pb * pc * (1 - pd) * N
            e1100 = pa * pb * (1 - pc) * (1 - pd) * N
            e0111 = (1 - pa) * pb * pc * pd * N
            e1110 = pa * pb * pc * (1 - pd) * N
            e1111 = pa * pb * pc * pd * N
            
            log1 = o1111 * (log(o1111, 10) - log(e1111, 10))
            log2 = o0001 * (log(o0001, 10) - log(e0001, 10))
            log3 = o0010 * (log(o0010, 10) - log(e0010, 10))
            log4 = o0100 * (log(o0100, 10) - log(e0100, 10))
            log5 = o1000 * (log(o1000, 10) - log(e1000, 10))
            log6 = o0011 * (log(o0011, 10) - log(e0011, 10))
            log7 = o0110 * (log(o0110, 10) - log(e0110, 10))
            log8 = o1100 * (log(o1100, 10) - log(e1100, 10))
            log9 = o0111 * (log(o0111, 10) - log(e0111, 10))
            log10 = o1110 * (log(o1110, 10) - log(e1110, 10))
            log11 = o0000 * (log(o0000, 10) - log(e0000, 10))
            ll = log1 + log2 + log3 + log4 + log5 + log6 + log7 + log8 + log9 + log10 + log11
            if ll >= threshold:
               tetragramFeatures.add(k)                           

      #finally, add the features         
      for ex in newTable:
         if not preprocessor:
            phrases = p.split(ex['text'].value.decode('utf-8','ignore').encode('cp1250','ignore'))
         else:
            phrases = preprocessor.removeStopwords(preprocessor.tokenize(preprocessor.lemmatize(preprocessor.lowercase(ex['text'].value))))
         #sad imam tokene, makni prazne stringove
         phrases = [i for i in phrases if i]
         localtetragrams = {}
         for phrase in phrases:
            i = 0
            tokens = ps.split(phrase)
            tokens = [tok for tok in tokens if tok]
            while i < len(tokens) - 3:
                if tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2] + ' ' + tokens[i+3] in tetragramFeatures:
                   localtetragrams[tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2] + ' ' + tokens[i+3]] = localtetragrams.get(tokens[i] + ' ' + tokens[i+1] + ' ' + tokens[i+2] + ' ' + tokens[i+3], 0) + 1.0
                i += 1
            
         for k in localtetragrams.keys():
            id = tetragrams.get(k, 0)
            if not id:
               id = orange.newmetaid()
               tetragrams[k] = id
            ex[id] = localtetragrams[k]

      newTable.domain.addmetas(dict([(id, orange.FloatVariable(k)) for k, id in tetragrams.items()]), TEXTMETAID)
   else:
      return table
   table.changeDomain(domaincopy)
   return newTable


def extractNames(text):
   """Return a list of named entities. This function is called by
    extractNamedEntities function. """

   in1 = set('.!?()[]{}/\\<>:;')
   in2 = set(',\'"')
   name = ''
   names = []
   state = 0
   for letter in text:
      if state == 0:
         if letter.isalnum():
            state = 4
      elif state == 1:
         if letter.isupper(): #or isdigit
            state = 2
            name += letter
         elif letter in in1:
            state = 0
      elif state == 2:
         if letter.isspace():
            name += ' '
            state = 3
         elif letter in in1:
            state = 0
            names.append(name)
            name = ''
         elif letter.islower() or letter.isupper() or letter.isdigit():
            name += letter
         elif letter in in2:
            name += letter
            state = 3
      elif state == 3:
         if letter.islower() or letter in in1 or letter.isdigit():
            names.append(name[:-1])
            name = ''
            state = 1
         elif letter.isupper():# or letter.isdigit()
            name += letter
            state = 2
         elif letter.isspace() or letter in in2:
            name += letter
      elif state == 4:
         if letter.isspace() or letter in in1 or letter in in2:
            state = 1
            
   if name:
      names.append(name)
   return [w.rstrip(',\'" ') for w in names]


def extractNamedEntities(table, preprocessor = None, stopwords = None, callback = None):
   """Adds named entities to an ExampleTable in a similar way bagOfWords adds
    words."""
    
   p = re.compile('[\.,!?(){}:; \n\r\t"]')
   na = re.compile('\\W')
   domaincopy = orange.Domain(table.domain)
   newTable = orange.ExampleTable(table)
   #newTable.domain = orange.Domain(table.domain)

   allNames = {}
   for ex in newTable:
      if not preprocessor:
         tokens = p.split(ex['text'].value.decode('utf-8','ignore').encode('cp1250','ignore'))
      else:
         tokens = preprocessor.removeStopwords(preprocessor.tokenize(preprocessor.lemmatize(preprocessor.lowercase(ex['text'].value))))
         
      flag = False
      hadName = False
      names = {}
      name = ''
      for token in tokens:
         if flag and token and (token[0].isupper() or token[0].isdigit()):
            name += token + ' '
            hadName = True
         elif hadName:
            if name[:-1].find(' ') == -1 and (len(name) <= 4 or name.isdigit()):
               pass
            else:
               names[name] = names.get(name, 0) + 1.0
            name = ''
            hadName = False
         flag = token

      text = ex['text'].value.decode('utf-8','ignore').encode('cp1250','ignore')
      names = extractNames(text)
      #some postprocessing is in order, remove stopwords and one-letter words
      if stopwords:
        names = [n for n in names if n.lower() not in stopwords]
      names = [n for n in names if len(n) > 1]
      names = dict([(n, float(text.count(n))) for n in names])         
      #exdomain = ex.domain
      for k in names.keys():
         id = allNames.get(k, 0)
         if not id:
            id = orange.newmetaid()
            allNames[k] = id
         ex[id] = names[k]

   newTable.domain.addmetas(dict([(id, orange.FloatVariable(k)) for k, id in allNames.items()]), TEXTMETAID)
   #table.domain = orange.Domain(domaincopy)
   table.changeDomain(domaincopy)
   #table.domain.removemeta(table.domain.getmetas(TEXTMETAID).keys())
   return newTable


   
# implementation of "Multinominal Naive Bayes" for text mining
# source from Witten & Frank - Data mining: Practical Machine Learning Tools and Techniques, page 94
# Crt Gorup crt(dot)gorup(at)gmail(dot)com, Albacete 2/4/2008
# used trick (in order to avoid underflow): log(p(d|c)) = log(c) + sum F_i*log(p(w_i|c))

class TextLearner(object):
   def __new__(cls,examples=None,name='multinomial naive bayes', **kwds):
      learner = object.__new__(cls, **kwds)
      if examples:
         learner.__init__(name)
         return learner(examples)
      else:
         return learner

   def __init__(self,name='multinomial naive bayes'):
      self.name = name

   def __call__(self,data,weight=None):
      domain = data.domain
      noClasses = len(domain.classVar.values)

      n_class = [0.]*noClasses               # # of document per class
      words_domain = [a[1].name for a in data.domain.getmetas().items()] # all words in domain

      for e in data:
         n_class[int(e.getclass())] += 1

      # aprior class probability
      p_class = [0.]* noClasses             # apriori class probability
      n_words_class = [0.]*noClasses         # total number of words per class
      n_words_cond_class = [0.]*noClasses
      p_words_cond_class = [0.]*noClasses

      for i in range(noClasses):
         p_class[i] = log((1+n_class[i]) / (len(data)+noClasses))     # log applied ! + Laplace estimate
         # print "class ",  i , "  ", exp(p_class[i])
         n_words_cond_class[i] = dict()      # a dict to keep freq of words per class
         p_words_cond_class[i] = dict()      # a dict to keep cond probability of words per class

      # conditional class probability p(word|class)
      for e in data:
         cid = int(e.getclass())
         for i,g in e.getmetas(7).items():
            nm = g.variable.name
            fr = g.value
            if not n_words_cond_class[cid].has_key(nm):
               n_words_cond_class[cid][nm] = 0.0

            # increase n(word|class) cunter
            n_words_cond_class[cid][nm] += fr
            # increase words in class counter
            n_words_class[cid] += fr

      # calculate conditional probability
      for i in range(len(n_words_class)):    # for each class
         for e in words_domain: # for each word in domain
            if e in n_words_cond_class[i].keys():  # this word was fund in a leasning set
               p_words_cond_class[i][e] = log( (1 + n_words_cond_class[i][e]) / (n_words_class[i] + len(words_domain) ))  # log applied log(p(w|c_i))
            else:
               p_words_cond_class[i][e] = log(1.0 / (n_words_class[i] + len(words_domain))) # laplace estimate

      return TextClassifier(domain=domain, p_class=p_class, p_cond=p_words_cond_class, name=self.name) # we return a classifier

class TextClassifier(object):
   def __init__(self,**kwds):
      self.__dict__ = kwds

   def __call__(self, example,result_type=orange.GetValue):
      # we have to classify example
      #p = map(None,self.p_class)
      # for each word in example

      p = [0.0] * len(self.p_class)
      p_final =[0.0] * len(self.p_class)

      for c in range(len(self.domain.classVar.values)):
         for i,g in example.getmetas(7).items():
            w = g.variable.name
            fr = g.value    
            if self.p_cond[c].has_key(w):
               p[c] += (fr * self.p_cond[c][w])

      maxp = max(p)

      for i in range(len(self.p_class)):
         p_final[i] = exp(self.p_class[i]) * exp(p[i] - maxp) # patch to increase all the probablilities

      # use exp to convert back to numbers
      #p = map(exp,p)
      #print p
      # normalize probabilities to sum to 1
      sump = sum(p_final)
      if sump>0:
        for i in range(len(p_final)): p_final[i] = p_final[i]/sump
      #print p

      # find the class with highest probability
      v_index = p_final.index(max(p_final))
      v = orange.Value(self.domain.classVar, v_index)

      # return the value based on requested return type
      if result_type == orange.GetValue:
        return v
      if result_type == orange.GetProbabilities:
        return p_final
      return (v,p_final)

   def show(self):
      print "class prob=", map(exp,self.p_class)
      print "log cond prob=", self.p_cond
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.