├── LICENSE ├── README.md ├── decompound_secos.py ├── decompound_server.py ├── decompound_text_secos.py ├── eval_decompounding.py ├── eval_decompounding_wilcoxon.py └── generateDecompoundCandidates.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SECOS - SEmantic COmpound Splitter 2 | 3 | SECOS is an unsupervised compound splitter that uses information from a distributional thesaurus (DT). Details about its working can be found in our [paper](https://www.inf.uni-hamburg.de/en/inst/ab/lt/publications/2016-riedletal-naacl.pdf). 4 | 5 | 6 | Table of Content 7 | ================ 8 | 9 | 10 | * [Split compounds](#split-compounds) 11 | * [Apply SECOS to German Compounds](#apply-secos-to-german-compounds) 12 | * [Apply SECOS to Dutch Compounds](#apply-secos-to-dutch-compounds) 13 | * [Decompound text](#decompound-server) 14 | * [Decompound server](#decompound-server) 15 | * [Significance testing](#significance-testing) 16 | * [Precomputed models](#precomputed-models) 17 | * [Datasets for Evaluation](#datasets-for-evaluation) 18 | * [Citation](#citation) 19 | * [License](#license) 20 | 21 | 22 | 23 | Split compounds 24 | =============== 25 | 26 | In order to split compounds SECOS features some parameters and requires a candidate file, which is generated using a distributional thesaurus. In order to use SECOS for splitting German and Dutch compounds, you can use pre-computed candidate lists and the commands shown below. 27 | 28 | ``` 29 | python decompound_secos.py dt_candidates word_count_file min_word_count(50) file_compound word_index prefix_length(3) suffix_length(3) word_length(5) dash_word(3) upper(upper) epsilon 30 | ----------------------------------------------------- 31 | Parameter description: 32 | ----------------------------------------------------- 33 | dt_candidates: file with words and their split candidates, generated from a distributional thesaurus (DT) 34 | word_count_file: file with word counts used for filtering 35 | min_word_count: minimal word count used for split candidates (recommended paramater: 50) 36 | file_compound: file with words that should be decompounded (each compound needs to be in a single line) 37 | word_index: index of the word in the tab separated file_compound 38 | prefix_length: length of prefixes that are appended to the right-sided word (recommended parameter: 3) 39 | suffix_length: length of suffixes that are appended to the left-sided word (recommended parameter: 3) 40 | word_length: minimal word length that is used from the split candidates (recommended parameter: 5) 41 | dash_word: heuristic to split words with dash, which has no big impact (recommended: 3) 42 | upper: consider uppercase letters (=upper) or not (=lower). Should be set for case-sensitive languages e.g. German 43 | epsilon: smoothing factor (recommended parameter: 0.01 44 | ``` 45 | 46 | Apply SECOS to German Compounds 47 | =============================== 48 | 49 | In order to compound German words you need to download and unzip the following package: [data.zip](https://ltmaggie.informatik.uni-hamburg.de/files/SECOS/data.zip). Using these files, a list of compounds (german_compounds) can be split using the following command: 50 | 51 | 52 | ``` 53 | python decompound_secos.py data/denews70M_trigram__candidates data/denews70M_trigram__WordCount 50 german_compounds 0 3 3 5 3 upper 0.01 > output 54 | ``` 55 | 56 | For explaining the output, we also define an examplary german_compounds file with the following content: 57 | 58 | ``` 59 | Donaudampfschifffahrtsgesellschaftskapitän 60 | Hefeweizenbier 61 | ``` 62 | 63 | Executing SECOS, we retrieve the file output has the following content: 64 | 65 | 66 | ``` 67 | U Donau-dampf-schifffahrts-gesellschafts-kapitän U Donau-dampf-schifffahrts-gesellschafts-kapitän Donaudampfschifffahrtsgesellschaftskapitän Donaudampfschifffahrtsgesellschaftskapitän Donaudampfschifffahrtsgesellschaftskapitän Donau-dampf-schifffahrts-gesellschafts-kapitän -1 Donaudampfschifffahrtsgesellschaftskapitän 68 | U Hefe-weizen-bier U Hefe-weizen-bier Hefeweizenbier Hefeweizenbier Hefeweizenbier Hefe-weizen-bier 2 Hefeweizenbier 69 | ``` 70 | 71 | with the following columns: 72 | 73 | ``` 74 | 1) Method that was considered best for the compounding 75 | following possibilities: 76 | C1: use similar candidate units 77 | C2: use extended similar candidate units 78 | C3: use combination of C1 and C2 79 | U: Use the generated dictionary method 80 | 2) Splitted word using method described in column 1) 81 | 3) Method that performs the most splits (same abbreviations like 1) 82 | 4) Splitted word using method described in column 3) 83 | 5) Split compound using C1 84 | 6) Split compound using C2 85 | 7) Split compound using C3 86 | 8) Split compound using U 87 | 9) Word frequency of the word considered 88 | 10) the line of the input file 89 | ``` 90 | 91 | 92 | Apply SECOS to Dutch Compounds 93 | ============================== 94 | 95 | In order to compound Dutch words you need to download and unzip the following package: [data.zip](https://ltmaggie.informatik.uni-hamburg.de/files/SECOS/data.zip). Using these files, a list of compounds (dutch_compounds) can be split using the following command: 96 | 97 | ``` 98 | python decompound_secos.py data/dutchCoW_trigram__candidates data/dutchCoW_trigram__WordCount 50 dutch_compounds 0 3 3 5 3 lower 0.01 99 | ``` 100 | 101 | For more information about input and output read the example on applying SECOS to German. 102 | 103 | ## Training Candidates for New Language 104 | In order to train candidates for a new language, a distributional thesaurus (DT) is required. The DT is a file of 3 tab separated columns with two words and their similarity score. The file needs to be ordered by the first word and the similarity score in descending ordering. The DT is generated using JoBimText (www.jobimtext.org) using only neighboring words by using the Trigram holing operation. 105 | Using such a DT the candidates can easily be generated with the following command: 106 | 107 | ``` 108 | cat dt | python generateDecompoundCandidates.py > dt_candidates 109 | ``` 110 | 111 | Decompound text 112 | =============== 113 | 114 | For decompounding from the STDIN using the best option you can use the following python script which has similar parameters as the script above: 115 | 116 | ``` 117 | echo "Ich esse gerne Zitroneneis" | python decompound_text_secos.py dt_candidates word_count_file min_word_count(50) prefix_length(3) suffix_length(3) word_length(5) dash_word(3) upper(upper) epsilon 118 | ----------------------------------------------------- 119 | Parameter description: 120 | ----------------------------------------------------- 121 | dt_candidates: file with words and their split candidates, generated from a distributional thesaurus (DT) 122 | word_count_file: file with word counts used for filtering 123 | min_word_count: minimal word count used for split candidates (recommended paramater: 50) 124 | prefix_length: length of prefixes that are appended to the right-sided word (recommended parameter: 3) 125 | suffix_length: length of suffixes that are appended to the left-sided word (recommended parameter: 3) 126 | word_length: minimal word length that is used from the split candidates (recommended parameter: 5) 127 | dash_word: heuristic to split words with dash, which has no big impact (recommended: 3) 128 | upper: consider uppercase letters (=upper) or not (=lower). Should be set for case-sensitive languages e.g. German 129 | epsilon: smoothing factor (recommended parameter: 0.01 130 | ``` 131 | 132 | Using the German model the following command can be used: 133 | 134 | ``` 135 | echo "Ich esse gerne Zitroneneis" | python decompound_text_secos.py denews70M_trigram__candidates denews70M_trigram__WordCount 50 3 3 5 3 upper 0.01 136 | ``` 137 | 138 | Decompound server 139 | ================= 140 | 141 | When you want to decompound many different documents, the decompounding can take quite some time. In order to reduce the time needed for decompounding, I provide some decompounding server. Thus, the model does not need to be loaded serveral times. In addition, all decompounded words are stored in memory, which speeds up the decompounding of text tremendously. The server can be started with the same parameters as the 'Decompound text' and has an additional parameter for the port the server should run. 142 | 143 | ``` 144 | python decompound_server.py dt_candidates word_count_file min_word_count(50) prefix_length(3) suffix_length(3) word_length(5) dash_word(3) upper(upper) epsilon port 145 | ----------------------------------------------------- 146 | Parameter description: 147 | ----------------------------------------------------- 148 | dt_candidates: file with words and their split candidates, generated from a distributional thesaurus (DT) 149 | word_count_file: file with word counts used for filtering 150 | min_word_count: minimal word count used for split candidates (recommended paramater: 50) 151 | prefix_length: length of prefixes that are appended to the right-sided word (recommended parameter: 3) 152 | suffix_length: length of suffixes that are appended to the left-sided word (recommended parameter: 3) 153 | word_length: minimal word length that is used from the split candidates (recommended parameter: 5) 154 | dash_word: heuristic to split words with dash, which has no big impact (recommended: 3) 155 | upper: consider uppercase letters (=upper) or not (=lower). Should be set for case-sensitive languages e.g. German 156 | epsilon: smoothing factor (recommended parameter: 0.01 157 | ``` 158 | 159 | Using the German model the server can be started as follows: 160 | 161 | ``` 162 | python decompound_server.py denews70M_trigram__candidates denews70M_trigram__WordCount 50 3 3 5 3 upper 0.01 2020 163 | ``` 164 | 165 | Once the server is running queries can be performed as following: 166 | 167 | ``` 168 | curl localhost:2020?sentence=Hefeweizenbier 169 | ``` 170 | 171 | and will return the decompounded word using whitespaces: 172 | 173 | ``` 174 | Hefe weizen bier 175 | ``` 176 | 177 | 178 | Evaluation 179 | ========== 180 | 181 | 182 | 183 | For the evaluation the python script eval_decompounding.py can be used. It expects as stdin a tab separated file including the gold standard and the predicted splits which are separated with dashs (-). 184 | 185 | Here an example for a compound file (compound_file) where column 1 contains the predicted splits and column 2 the gold standard split 186 | 187 | ``` 188 | cat compound_file | python eval_decompounding.py 1 2 189 | ``` 190 | 191 | This command results to the following output (precision, recall and F1 measure based on the splits (the third row rounds to 4 digits). The last column presents the number of compounds considered and the amount of entirely correctly split compounds as well as the rate of correct split compounds. 192 | 193 | ``` 194 | Precision Recall F1 195 | 0.986667 0.964335 0.975373 196 | 0.9867 & 0.9643& 0.9754 197 | Considered Correct Percentage of Correct ones 198 | 700.000000 662.000000 0.945714 199 | 200 | ``` 201 | 202 | A detailed output of correct and false splits can be enabled by providing a third parameter: 203 | 204 | ``` 205 | cat compound_file | python eval_decompounding.py 1 2 debug 206 | ``` 207 | 208 | 209 | Significance testing 210 | ======================================== 211 | 212 | In addition to the above evaluation script, we also provide an evaluation script that can be used to compute a significance test between two methods. For this we use a Wilcoxon rank sum test and compare the performance based on the F1 score of each split compound. The test can be started using the following command: 213 | 214 | ``` 215 | python eval_decompounding_wilcoxon.py compound_file_1 predicted_compound gold_compound compound_file_2 predicted_compound gold_compound 216 | ``` 217 | 218 | 219 | Precomputed Models 220 | ===================== 221 | 222 | We provide precomputed models for German and Dutch, which can be downloaded here: [data.zip](https://ltmaggie.informatik.uni-hamburg.de/files/SECOS/data.zip) 223 | 224 | In addition, we have computed further models using Wikipedia for various languages. In order to compute similarities, we have either used JoBimText or Word2Vec. The different models are [here](http://ltdata1.informatik.uni-hamburg.de/SECOS) for the following languages: 225 | 226 | | Language | Abbreviation | 227 | | ------------- | ------------- | 228 | | Danish | da | 229 | | German | de | 230 | | English | en | 231 | | Spanish | es | 232 | | Estonian | et | 233 | | Farsi | fa | 234 | | Finnish | fi | 235 | | Hungarian | hu | 236 | | Latin | la | 237 | | Latvian | lv | 238 | | Netherland | nl | 239 | | Norway | no | 240 | | Swedish | sv | 241 | 242 | 243 | Datasets for Evaluation 244 | ===================== 245 | 246 | In order to perform an evaluation based on several languages in an automatic fashion, we have extracted compound words from Wiktionary for various langauges. These are available here: [datasets](http://ltdata1.informatik.uni-hamburg.de/SECOS/datasets/) 247 | 248 | Citation 249 | ======== 250 | 251 | If you use SECOS, please cite the following work: 252 | 253 | ``` 254 | @inproceedings{riedl2016secos, 255 | title={Unsupervised Compound Splitting With Distributional Semantics Rivals Supervised Methods }, 256 | author={Martin Riedl, Chris Biemann}, 257 | booktitle={Proceedings of The 15th Annual Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologie}, 258 | pages={617--622}, 259 | year={2016}, 260 | address={San Diego, CA, USA}, 261 | } 262 | ``` 263 | 264 | License 265 | ======= 266 | 267 | Apache License (ASL) 2.0 268 | -------------------------------------------------------------------------------- /decompound_secos.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import re 4 | import gzip 5 | 6 | i=0 7 | 8 | if len(sys.argv)<11: 9 | sys.stderr.write( "python "+sys.argv[0]+" dt_candidates word_count_file min_word_count(50) file_compound word_index prefix_length(3) suffix_length(3) word_length(5) dash_word(3) upper(upper) epsilon\n") 10 | sys.stderr.write("-----------------------------------------------------\n") 11 | sys.stderr.write("Parameter description:\n") 12 | sys.stderr.write("-----------------------------------------------------\n") 13 | sys.stderr.write("dt_candidates:\t\tfile with words and their split candidates, generated from a distributional thesaurus (DT)\n") 14 | sys.stderr.write("word_count_file:\tfile with word counts used for filtering\n") 15 | sys.stderr.write("min_word_count:\t\tminimal word count used for split candidates (recommended paramater: 50)\n") 16 | sys.stderr.write("file_compound:\t\tfile with words that should be decompounded (each compound needs to be in a single line)\n") 17 | sys.stderr.write("word_index:\t\tindex of the word in the tab separated file_compound\n") 18 | sys.stderr.write("prefix_length:\t\tlength of prefixes that are appended to the right-sided word (recommended parameter: 3)\n") 19 | sys.stderr.write("suffix_length:\t\tlength of suffixes that are appended to the left-sided word (recommended parameter: 3)\n") 20 | sys.stderr.write("word_length:\t\tminimal word length that is used from the split candidates (recommended parameter: 5)\n") 21 | sys.stderr.write("dash_word:\t\theuristic to split words with dash, which has no big impact (recommended: 3)\n") 22 | sys.stderr.write("upper:\t\t\tconsider uppercase letters (=upper) or not (=lower). Should be set for case-sensitive languages e.g. German\n") 23 | sys.stderr.write("epsilon:\t\tsmoothing factor (recommended parameter: 0.01\n") 24 | sys.exit(0) 25 | file_knowledge = sys.argv[1] 26 | file_wordcount = sys.argv[2] 27 | min_word_count = int(sys.argv[3]) 28 | file_compound = sys.argv[4] 29 | word_index_file_compound = int(sys.argv[5]) 30 | 31 | 32 | prefix_length = int(sys.argv[6]) 33 | suffix_length = int(sys.argv[7]) 34 | min_word_length = int(sys.argv[8]) 35 | epsilon = float(sys.argv[11]) 36 | #sys.stderr.write(str(epsilon)+"\t:epsilon") 37 | #1 -> remove, 2 -> split, 3 -> nothing 38 | dash_words = int(sys.argv[9]) 39 | uppercaseFirstLetter=False 40 | if sys.argv[10]=="upper": 41 | uppercaseFirstLetter=True 42 | 43 | 44 | debug = True 45 | debug = False 46 | 47 | def nopen(f): 48 | if f.endswith(".gz"): 49 | return gzip.open(f) 50 | return open(f) 51 | 52 | words = set() 53 | total_word_count = 0 54 | word_count = {} 55 | for l in nopen(file_wordcount): 56 | ls = l.strip().split("\t") 57 | wc = int(ls[1]) 58 | #if wc >=min_word_count: 59 | word_count[ls[0]]=wc 60 | total_word_count+=wc 61 | 62 | def removeWord(w): 63 | if len(w.replace("-",""))==0: 64 | return True 65 | if min_word_count <=0: 66 | return False 67 | if w in word_count: 68 | if word_count[w]>=min_word_count: 69 | return False 70 | 71 | return True 72 | def bylength(word1,word2): 73 | return len(word2)-len(word1) 74 | 75 | def removeShortAndEqual(wc,ws): 76 | nws=set() 77 | for w in ws: 78 | if len(w)>=min_word_length and w.lower()!=wc.lower() and not w.isupper() and w.lower() in wc.lower(): 79 | nws.add(w) 80 | return list(nws) 81 | #count suffixes and prefixes 82 | fillers = {} 83 | def addUp(w): 84 | if w in fillers: 85 | fillers[w]+=1 86 | else: 87 | fillers[w]=1 88 | def appendSuffix(w): 89 | nl = "" 90 | #first append on the left side 91 | for l in w.split("-"): 92 | if len(l)>suffix_length: 93 | nl+="-" 94 | else: 95 | addUp(l) 96 | nl+=l 97 | nl = nl.strip("-") 98 | return nl 99 | 100 | def appendPrefix(w): 101 | #append to the right 102 | nw = w 103 | nl = "" 104 | for l in nw.split("-"): 105 | nl+=l 106 | if len(l)>prefix_length: 107 | nl+="-" 108 | if nl.endswith("-"): 109 | nl = nl[:-1] 110 | return nl 111 | def getWordCounts(comp): 112 | sum = 1 113 | for c in comp.split("-"): 114 | if uppercaseFirstLetter: 115 | c = c[0].upper()+c[1:] 116 | if c in word_count: 117 | sum*=(word_count[c]+epsilon)/(total_word_count+epsilon*len(word_count)) 118 | else: 119 | sum*=epsilon/(total_word_count+epsilon*len(word_count)) 120 | return pow(1.0*sum,1.0/len(comp.split("-"))) 121 | 122 | def appendSuffixAndPrefix(w): 123 | sp = appendSuffix(appendPrefix(w)) 124 | ps = appendPrefix(appendSuffix(w)) 125 | spc = getWordCounts(sp) 126 | psc = getWordCounts(ps) 127 | #if w.replace("-","")=="Regionalliga": 128 | # print "REGIONAL" 129 | # print spc 130 | # print psc 131 | # print sp 132 | # print ps 133 | if spc>psc: 134 | return sp 135 | return ps 136 | 137 | def generateCompound(w,ws): 138 | #remove too short words 139 | #if debug: sys.out.write(ws 140 | nws = removeShortAndEqual(w,ws) 141 | #print nws 142 | if len(nws)==0: 143 | 144 | if debug: sys.stderr.write( "NONE: "+w+"\n") 145 | return None 146 | nws_sorted = sorted(nws,cmp=bylength,reverse=True) 147 | #get split points 148 | splits=set() 149 | for n in nws_sorted: 150 | if not n.lower() in w.lower(): 151 | continue 152 | 153 | idx = w.lower().index(n.lower()) 154 | splits.add(idx) 155 | splits.add(idx+len(n)) 156 | splits_sorted = sorted(list(splits)) 157 | #print nws_sorted 158 | #print splits_sorted 159 | wc = "" 160 | prev = 0 161 | for i in splits_sorted: 162 | if i==0: 163 | continue 164 | wc += w[prev:i]+"-" 165 | prev = i 166 | wc +=w[prev:] 167 | if wc.endswith("-"): 168 | wc = wc[:-1] 169 | return wc 170 | 171 | def addCompound(comp,w,ws): 172 | if ws !=None: 173 | ws_merged = appendSuffixAndPrefix(ws) 174 | comp[w]=ws_merged 175 | if debug:sys.stderr.write( "Result: "+w+"\t"+ws+"\t"+ws_merged+"\n") 176 | def processCompound(comp,w,wns): 177 | wns_split = wns.split(" ") 178 | if "-" in w and dash_words ==1: 179 | return 180 | if dash_words ==2: 181 | ws = w.split("-") 182 | for wi in ws: 183 | res = generateCompound(wi,wns_split) 184 | addCompound(comp,wi,res) 185 | return 186 | res = generateCompound(w,wns_split) 187 | addCompound(comp,w,res) 188 | comp1 = {} 189 | comp2 ={} 190 | comp3 = {} 191 | sys.stderr.write("read knowledge\n") 192 | for l in nopen(file_knowledge): 193 | ls = l.rstrip("\n").split("\t") 194 | w = ls[0] 195 | if not removeWord(w): 196 | processCompound(comp1,w,ls[1]) 197 | processCompound(comp2,w,ls[2]) 198 | processCompound(comp3,w,ls[3]) 199 | sys.stderr.write("extract single words\n") 200 | singlewords = set() 201 | for c in comp1: 202 | if "-" in comp1[c]: 203 | singlewords|=set(comp1[c].split("-")) 204 | sys.stderr.write("decompound\n") 205 | #k = nopen("singlewords_martin","w") 206 | #for s in singlewords: 207 | # k.write(s+"\n") 208 | #close(k) 209 | def containedIn(c,cands): 210 | for cj in cands: 211 | if c.lower() in cj.lower() and c.lower()!=cj.lower(): 212 | return True 213 | return False 214 | def unknownWordCompounding(w): 215 | cands = set() 216 | for s in singlewords: 217 | if s.lower() in w.lower()and not s.lower()==w.lower(): 218 | cands.add(s) 219 | cands_new = set() 220 | for ci in cands: 221 | if not containedIn(ci,cands): 222 | cands_new.add(ci) 223 | res = generateCompound(w,cands_new) 224 | if debug: sys.stderr.write("unknown1: "+res+"\n") 225 | if res==None: 226 | res = w 227 | else: 228 | res = appendSuffixAndPrefix(res) 229 | if debug: sys.stderr.write("unknown2: "+res+"\n") 230 | return [res,cands_new] 231 | 232 | def getFirstDash(compounds): 233 | i = 0 234 | for c in compounds: 235 | if "-" in c: 236 | return i 237 | i+=1 238 | return -1 239 | def getMaxIdx(ls): 240 | idx = -1 241 | val = 0 242 | i=0 243 | for l in ls: 244 | if l>val: 245 | val = l 246 | idx = i 247 | i+=1 248 | return [idx,val] 249 | 250 | def getHighestProb(compounds): 251 | probs = [] 252 | for c in compounds: 253 | p = getWordCounts(c) 254 | #if not "-" in c: 255 | # p = p*-1 256 | probs.append(p) 257 | return getMaxIdx(probs) 258 | 259 | 260 | for l in nopen(file_compound): 261 | ls = l.strip().split("\t") 262 | w = ls[word_index_file_compound] 263 | wc = -1 264 | if w in word_count: 265 | wc = word_count[w] 266 | c1 = comp1.get(w,w) 267 | c2 = comp2.get(w,w) 268 | c3 = comp3.get(w,w) 269 | [u,ufeats]=unknownWordCompounding(w) 270 | prefix = "W" 271 | cand = w 272 | feats = "" 273 | cands = [c1,c2,c3,u] 274 | cands_str = ["C1","C2","C3","U"] 275 | idx = getFirstDash(cands) 276 | if idx>=0: 277 | cand = cands[idx] 278 | prefix = cands_str[idx] 279 | [idx,prob] = getHighestProb(cands) 280 | pcand = w 281 | pprefix = "W" 282 | if idx>=0: 283 | #print cands 284 | #print idx 285 | pcand = cands[idx] 286 | pprefix = cands_str[idx] 287 | 288 | #print "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%d\t%s" %(pprefix,pcand,prefix,cand,c1,c2,c3,u,wc,l.strip(),wc,ufeats) 289 | print "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%d\t%s" %(pprefix,pcand,prefix,cand,c1,c2,c3,u,wc,l.strip()) 290 | 291 | 292 | 293 | -------------------------------------------------------------------------------- /decompound_server.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import re 4 | import gzip 5 | from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 6 | from urlparse import urlparse, parse_qs 7 | import SocketServer 8 | 9 | 10 | i=0 11 | 12 | if len(sys.argv)<9: 13 | sys.stderr.write( "python "+sys.argv[0]+" dt_candidates word_count_file min_word_count(50) prefix_length(3) suffix_length(3) word_length(5) dash_word(3) upper(upper) epsilon port\n") 14 | sys.stderr.write("-----------------------------------------------------\n") 15 | sys.stderr.write("Parameter description:\n") 16 | sys.stderr.write("-----------------------------------------------------\n") 17 | sys.stderr.write("dt_candidates:\t\tfile with words and their split candidates, generated from a distributional thesaurus (DT)\n") 18 | sys.stderr.write("word_count_file:\tfile with word counts used for filtering\n") 19 | sys.stderr.write("min_word_count:\t\tminimal word count used for split candidates (recommended paramater: 50)\n") 20 | sys.stderr.write("prefix_length:\t\tlength of prefixes that are appended to the right-sided word (recommended parameter: 3)\n") 21 | sys.stderr.write("suffix_length:\t\tlength of suffixes that are appended to the left-sided word (recommended parameter: 3)\n") 22 | sys.stderr.write("word_length:\t\tminimal word length that is used from the split candidates (recommended parameter: 5)\n") 23 | sys.stderr.write("dash_word:\t\theuristic to split words with dash, which has no big impact (recommended: 3)\n") 24 | sys.stderr.write("upper:\t\t\tconsider uppercase letters (=upper) or not (=lower). Should be set for case-sensitive languages e.g. German\n") 25 | sys.stderr.write("epsilon:\t\tsmoothing factor (recommended parameter: 0.01\n") 26 | sys.stderr.write("port: Port the server will run") 27 | sys.exit(0) 28 | file_knowledge = sys.argv[1] 29 | file_wordcount = sys.argv[2] 30 | min_word_count = int(sys.argv[3]) 31 | 32 | 33 | prefix_length = int(sys.argv[4]) 34 | suffix_length = int(sys.argv[5]) 35 | min_word_length = int(sys.argv[6]) 36 | epsilon = float(sys.argv[9]) 37 | port = int(sys.argv[10]) 38 | #1 -> remove, 2 -> split, 3 -> nothing 39 | dash_words = int(sys.argv[7]) 40 | uppercaseFirstLetter=False 41 | if sys.argv[8]=="upper": 42 | uppercaseFirstLetter=True 43 | 44 | 45 | debug = True 46 | debug = False 47 | 48 | 49 | 50 | words = set() 51 | total_word_count = 0 52 | word_count = {} 53 | 54 | def nopen(f): 55 | if f.endswith(".gz"): 56 | return gzip.open(f) 57 | return open(f) 58 | 59 | for l in nopen(file_wordcount): 60 | ls = l.strip().split("\t") 61 | wc = int(ls[1]) 62 | #if wc >=min_word_count: 63 | word_count[ls[0]]=wc 64 | total_word_count+=wc 65 | 66 | def removeWord(w): 67 | if len(w.replace("-",""))==0: 68 | return True 69 | if min_word_count <=0: 70 | return False 71 | if w in word_count: 72 | if word_count[w]>=min_word_count: 73 | return False 74 | 75 | return True 76 | def bylength(word1,word2): 77 | return len(word2)-len(word1) 78 | 79 | def removeShortAndEqual(wc,ws): 80 | nws=set() 81 | for w in ws: 82 | if len(w)>=min_word_length and w.lower()!=wc.lower() and not w.isupper() and w.lower() in wc.lower(): 83 | nws.add(w) 84 | return list(nws) 85 | #count suffixes and prefixes 86 | fillers = {} 87 | def addUp(w): 88 | if w in fillers: 89 | fillers[w]+=1 90 | else: 91 | fillers[w]=1 92 | def appendSuffix(w): 93 | nl = "" 94 | #first append on the left side 95 | for l in w.split("-"): 96 | if len(l)>suffix_length: 97 | nl+="-" 98 | else: 99 | addUp(l) 100 | nl+=l 101 | nl = nl.strip("-") 102 | return nl 103 | 104 | def appendPrefix(w): 105 | #append to the right 106 | nw = w 107 | nl = "" 108 | for l in nw.split("-"): 109 | nl+=l 110 | if len(l)>prefix_length: 111 | nl+="-" 112 | if nl.endswith("-"): 113 | nl = nl[:-1] 114 | return nl 115 | def getWordCounts(comp): 116 | sum = 1 117 | for c in comp.split("-"): 118 | if uppercaseFirstLetter: 119 | c = c[0].upper()+c[1:] 120 | if c in word_count: 121 | sum*=(word_count[c]+epsilon)/(total_word_count+epsilon*len(word_count)) 122 | else: 123 | sum*=epsilon/(total_word_count+epsilon*len(word_count)) 124 | return pow(1.0*sum,1.0/len(comp.split("-"))) 125 | 126 | def appendSuffixAndPrefix(w): 127 | sp = appendSuffix(appendPrefix(w)) 128 | ps = appendPrefix(appendSuffix(w)) 129 | spc = getWordCounts(sp) 130 | psc = getWordCounts(ps) 131 | #if w.replace("-","")=="Regionalliga": 132 | if spc>psc: 133 | return sp 134 | return ps 135 | 136 | def generateCompound(w,ws): 137 | #remove too short words 138 | #if debug: sys.out.write(ws 139 | nws = removeShortAndEqual(w,ws) 140 | if len(nws)==0: 141 | 142 | if debug: sys.stderr.write( "NONE: "+w+"\n") 143 | return None 144 | nws_sorted = sorted(nws,cmp=bylength,reverse=True) 145 | #get split points 146 | splits=set() 147 | for n in nws_sorted: 148 | if not n.lower() in w.lower(): 149 | continue 150 | 151 | idx = w.lower().index(n.lower()) 152 | splits.add(idx) 153 | splits.add(idx+len(n)) 154 | splits_sorted = sorted(list(splits)) 155 | wc = "" 156 | prev = 0 157 | for i in splits_sorted: 158 | if i==0: 159 | continue 160 | wc += w[prev:i]+"-" 161 | prev = i 162 | wc +=w[prev:] 163 | if wc.endswith("-"): 164 | wc = wc[:-1] 165 | return wc 166 | 167 | def addCompound(comp,w,ws): 168 | if ws !=None: 169 | ws_merged = appendSuffixAndPrefix(ws) 170 | comp[w]=ws_merged 171 | if debug:sys.stderr.write( "Result: "+w+"\t"+ws+"\t"+ws_merged+"\n") 172 | def processCompound(comp,w,wns): 173 | wns_split = wns.split(" ") 174 | if "-" in w and dash_words ==1: 175 | return 176 | if dash_words ==2: 177 | ws = w.split("-") 178 | for wi in ws: 179 | res = generateCompound(wi,wns_split) 180 | addCompound(comp,wi,res) 181 | return 182 | res = generateCompound(w,wns_split) 183 | addCompound(comp,w,res) 184 | comp1 = {} 185 | comp2 ={} 186 | comp3 = {} 187 | sys.stderr.write("read knowledge\n") 188 | for l in open(file_knowledge): 189 | ls = l.rstrip("\n").split("\t") 190 | w = ls[0] 191 | if not removeWord(w): 192 | processCompound(comp1,w,ls[1]) 193 | processCompound(comp2,w,ls[2]) 194 | processCompound(comp3,w,ls[3]) 195 | sys.stderr.write("extract single words\n") 196 | singlewords = set() 197 | for c in comp1: 198 | if "-" in comp1[c]: 199 | singlewords|=set(comp1[c].split("-")) 200 | sys.stderr.write("start decompound process\n") 201 | #k = open("singlewords_martin","w") 202 | #for s in singlewords: 203 | # k.write(s+"\n") 204 | #close(k) 205 | def containedIn(c,cands): 206 | for cj in cands: 207 | if c.lower() in cj.lower() and c.lower()!=cj.lower(): 208 | return True 209 | return False 210 | def unknownWordCompounding(w): 211 | cands = set() 212 | for s in singlewords: 213 | if s.lower() in w.lower()and not s.lower()==w.lower(): 214 | cands.add(s) 215 | cands_new = set() 216 | for ci in cands: 217 | if not containedIn(ci,cands): 218 | cands_new.add(ci) 219 | res = generateCompound(w,cands_new) 220 | if debug: sys.stderr.write("unknown1: "+res+"\n") 221 | if res==None: 222 | res = w 223 | else: 224 | res = appendSuffixAndPrefix(res) 225 | if debug: sys.stderr.write("unknown2: "+res+"\n") 226 | return [res,cands_new] 227 | 228 | def getFirstDash(compounds): 229 | i = 0 230 | for c in compounds: 231 | if "-" in c: 232 | return i 233 | i+=1 234 | return -1 235 | def getMaxIdx(ls): 236 | idx = -1 237 | val = 0 238 | i=0 239 | for l in ls: 240 | if l>val: 241 | val = l 242 | idx = i 243 | i+=1 244 | return [idx,val] 245 | 246 | def getHighestProb(compounds): 247 | probs = [] 248 | for c in compounds: 249 | p = getWordCounts(c) 250 | #if not "-" in c: 251 | # p = p*-1 252 | probs.append(p) 253 | return getMaxIdx(probs) 254 | known_words = {} 255 | class Serv(BaseHTTPRequestHandler): 256 | 257 | def _set_headers(self): 258 | self.send_response(200) 259 | self.send_header('Content-type', 'text/html') 260 | self.end_headers() 261 | def do_GET(self): 262 | self._set_headers() 263 | query_components = parse_qs(urlparse(self.path).query) 264 | text = "" 265 | for w in query_components["sentence"][0].split(): 266 | if w in known_words: 267 | text+=" "+known_words[w] 268 | continue 269 | wc = -1 270 | if w in word_count: 271 | wc = word_count[w] 272 | c1 = comp1.get(w,w) 273 | c2 = comp2.get(w,w) 274 | c3 = comp3.get(w,w) 275 | [u,ufeats]=unknownWordCompounding(w) 276 | cand = w 277 | cands = [c1,c2,c3,u] 278 | idx = getFirstDash(cands) 279 | if idx>=0: 280 | cand = cands[idx] 281 | [idx,prob] = getHighestProb(cands) 282 | pcand = w 283 | if idx>=0: 284 | pcand = cands[idx] 285 | text+=" " + pcand.replace("-" ," ") 286 | known_words[w] = pcand.replace("-" ," ") 287 | self.wfile.write(text) 288 | # print "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%d\t%s" %(pprefix,pcand,prefix,cand,c1,c2,c3,u,l.strip(),wc,ufeats) 289 | 290 | def run(server_class=HTTPServer, handler_class=Serv, port=80): 291 | server_address = ('', port) 292 | httpd = server_class(server_address, handler_class) 293 | print 'Starting httpd using port '+str(port) 294 | httpd.serve_forever() 295 | run(port=port) 296 | -------------------------------------------------------------------------------- /decompound_text_secos.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import re 4 | 5 | i=0 6 | 7 | if len(sys.argv)<9: 8 | sys.stderr.write( "python "+sys.argv[0]+" dt_candidates word_count_file min_word_count(50) word_index prefix_length(3) suffix_length(3) word_length(5) dash_word(3) upper(upper) epsilon\n") 9 | sys.stderr.write("-----------------------------------------------------\n") 10 | sys.stderr.write("Parameter description:\n") 11 | sys.stderr.write("-----------------------------------------------------\n") 12 | sys.stderr.write("dt_candidates:\t\tfile with words and their split candidates, generated from a distributional thesaurus (DT)\n") 13 | sys.stderr.write("word_count_file:\tfile with word counts used for filtering\n") 14 | sys.stderr.write("min_word_count:\t\tminimal word count used for split candidates (recommended paramater: 50)\n") 15 | sys.stderr.write("prefix_length:\t\tlength of prefixes that are appended to the right-sided word (recommended parameter: 3)\n") 16 | sys.stderr.write("suffix_length:\t\tlength of suffixes that are appended to the left-sided word (recommended parameter: 3)\n") 17 | sys.stderr.write("word_length:\t\tminimal word length that is used from the split candidates (recommended parameter: 5)\n") 18 | sys.stderr.write("dash_word:\t\theuristic to split words with dash, which has no big impact (recommended: 3)\n") 19 | sys.stderr.write("upper:\t\t\tconsider uppercase letters (=upper) or not (=lower). Should be set for case-sensitive languages e.g. German\n") 20 | sys.stderr.write("epsilon:\t\tsmoothing factor (recommended parameter: 0.01\n") 21 | sys.exit(0) 22 | file_knowledge = sys.argv[1] 23 | file_wordcount = sys.argv[2] 24 | min_word_count = int(sys.argv[3]) 25 | 26 | 27 | prefix_length = int(sys.argv[4]) 28 | suffix_length = int(sys.argv[5]) 29 | min_word_length = int(sys.argv[6]) 30 | epsilon = float(sys.argv[9]) 31 | #1 -> remove, 2 -> split, 3 -> nothing 32 | dash_words = int(sys.argv[7]) 33 | uppercaseFirstLetter=False 34 | if sys.argv[8]=="upper": 35 | uppercaseFirstLetter=True 36 | 37 | 38 | debug = True 39 | debug = False 40 | 41 | def nopen(f): 42 | if f.endswith(".gz"): 43 | return gzip.open(f) 44 | return open(f) 45 | 46 | 47 | words = set() 48 | total_word_count = 0 49 | word_count = {} 50 | for l in nopen(file_wordcount): 51 | ls = l.strip().split("\t") 52 | wc = int(ls[1]) 53 | #if wc >=min_word_count: 54 | word_count[ls[0]]=wc 55 | total_word_count+=wc 56 | 57 | def removeWord(w): 58 | if len(w.replace("-",""))==0: 59 | return True 60 | if min_word_count <=0: 61 | return False 62 | if w in word_count: 63 | if word_count[w]>=min_word_count: 64 | return False 65 | 66 | return True 67 | def bylength(word1,word2): 68 | return len(word2)-len(word1) 69 | 70 | def removeShortAndEqual(wc,ws): 71 | nws=set() 72 | for w in ws: 73 | if len(w)>=min_word_length and w.lower()!=wc.lower() and not w.isupper() and w.lower() in wc.lower(): 74 | nws.add(w) 75 | return list(nws) 76 | #count suffixes and prefixes 77 | fillers = {} 78 | def addUp(w): 79 | if w in fillers: 80 | fillers[w]+=1 81 | else: 82 | fillers[w]=1 83 | def appendSuffix(w): 84 | nl = "" 85 | #first append on the left side 86 | for l in w.split("-"): 87 | if len(l)>suffix_length: 88 | nl+="-" 89 | else: 90 | addUp(l) 91 | nl+=l 92 | nl = nl.strip("-") 93 | return nl 94 | 95 | def appendPrefix(w): 96 | #append to the right 97 | nw = w 98 | nl = "" 99 | for l in nw.split("-"): 100 | nl+=l 101 | if len(l)>prefix_length: 102 | nl+="-" 103 | if nl.endswith("-"): 104 | nl = nl[:-1] 105 | return nl 106 | def getWordCounts(comp): 107 | sum = 1 108 | for c in comp.split("-"): 109 | if uppercaseFirstLetter: 110 | c = c[0].upper()+c[1:] 111 | if c in word_count: 112 | sum*=(word_count[c]+epsilon)/(total_word_count+epsilon*len(word_count)) 113 | else: 114 | sum*=epsilon/(total_word_count+epsilon*len(word_count)) 115 | return pow(1.0*sum,1.0/len(comp.split("-"))) 116 | 117 | def appendSuffixAndPrefix(w): 118 | sp = appendSuffix(appendPrefix(w)) 119 | ps = appendPrefix(appendSuffix(w)) 120 | spc = getWordCounts(sp) 121 | psc = getWordCounts(ps) 122 | #if w.replace("-","")=="Regionalliga": 123 | if spc>psc: 124 | return sp 125 | return ps 126 | 127 | def generateCompound(w,ws): 128 | #remove too short words 129 | #if debug: sys.out.write(ws 130 | nws = removeShortAndEqual(w,ws) 131 | if len(nws)==0: 132 | 133 | if debug: sys.stderr.write( "NONE: "+w+"\n") 134 | return None 135 | nws_sorted = sorted(nws,cmp=bylength,reverse=True) 136 | #get split points 137 | splits=set() 138 | for n in nws_sorted: 139 | if not n.lower() in w.lower(): 140 | continue 141 | 142 | idx = w.lower().index(n.lower()) 143 | splits.add(idx) 144 | splits.add(idx+len(n)) 145 | splits_sorted = sorted(list(splits)) 146 | wc = "" 147 | prev = 0 148 | for i in splits_sorted: 149 | if i==0: 150 | continue 151 | wc += w[prev:i]+"-" 152 | prev = i 153 | wc +=w[prev:] 154 | if wc.endswith("-"): 155 | wc = wc[:-1] 156 | return wc 157 | 158 | def addCompound(comp,w,ws): 159 | if ws !=None: 160 | ws_merged = appendSuffixAndPrefix(ws) 161 | comp[w]=ws_merged 162 | if debug:sys.stderr.write( "Result: "+w+"\t"+ws+"\t"+ws_merged+"\n") 163 | def processCompound(comp,w,wns): 164 | wns_split = wns.split(" ") 165 | if "-" in w and dash_words ==1: 166 | return 167 | if dash_words ==2: 168 | ws = w.split("-") 169 | for wi in ws: 170 | res = generateCompound(wi,wns_split) 171 | addCompound(comp,wi,res) 172 | return 173 | res = generateCompound(w,wns_split) 174 | addCompound(comp,w,res) 175 | comp1 = {} 176 | comp2 ={} 177 | comp3 = {} 178 | sys.stderr.write("read knowledge\n") 179 | for l in nopen(file_knowledge): 180 | ls = l.rstrip("\n").split("\t") 181 | w = ls[0] 182 | if not removeWord(w): 183 | processCompound(comp1,w,ls[1]) 184 | processCompound(comp2,w,ls[2]) 185 | processCompound(comp3,w,ls[3]) 186 | sys.stderr.write("extract single words\n") 187 | singlewords = set() 188 | for c in comp1: 189 | if "-" in comp1[c]: 190 | singlewords|=set(comp1[c].split("-")) 191 | sys.stderr.write("start decompound process\n") 192 | #k = nopen("singlewords_martin","w") 193 | #for s in singlewords: 194 | # k.write(s+"\n") 195 | #close(k) 196 | def containedIn(c,cands): 197 | for cj in cands: 198 | if c.lower() in cj.lower() and c.lower()!=cj.lower(): 199 | return True 200 | return False 201 | def unknownWordCompounding(w): 202 | cands = set() 203 | for s in singlewords: 204 | if s.lower() in w.lower()and not s.lower()==w.lower(): 205 | cands.add(s) 206 | cands_new = set() 207 | for ci in cands: 208 | if not containedIn(ci,cands): 209 | cands_new.add(ci) 210 | res = generateCompound(w,cands_new) 211 | if debug: sys.stderr.write("unknown1: "+res+"\n") 212 | if res==None: 213 | res = w 214 | else: 215 | res = appendSuffixAndPrefix(res) 216 | if debug: sys.stderr.write("unknown2: "+res+"\n") 217 | return [res,cands_new] 218 | 219 | def getFirstDash(compounds): 220 | i = 0 221 | for c in compounds: 222 | if "-" in c: 223 | return i 224 | i+=1 225 | return -1 226 | def getMaxIdx(ls): 227 | idx = -1 228 | val = 0 229 | i=0 230 | for l in ls: 231 | if l>val: 232 | val = l 233 | idx = i 234 | i+=1 235 | return [idx,val] 236 | 237 | def getHighestProb(compounds): 238 | probs = [] 239 | for c in compounds: 240 | p = getWordCounts(c) 241 | #if not "-" in c: 242 | # p = p*-1 243 | probs.append(p) 244 | return getMaxIdx(probs) 245 | 246 | 247 | for l in sys.stdin: 248 | text = "" 249 | for w in l.strip().split(): 250 | wc = -1 251 | if w in word_count: 252 | wc = word_count[w] 253 | c1 = comp1.get(w,w) 254 | c2 = comp2.get(w,w) 255 | c3 = comp3.get(w,w) 256 | [u,ufeats]=unknownWordCompounding(w) 257 | cand = w 258 | cands = [c1,c2,c3,u] 259 | idx = getFirstDash(cands) 260 | if idx>=0: 261 | cand = cands[idx] 262 | [idx,prob] = getHighestProb(cands) 263 | pcand = w 264 | if idx>=0: 265 | pcand = cands[idx] 266 | text+=" " + pcand.replace("-" ," ") 267 | print text.strip() 268 | # print "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%d\t%s" %(pprefix,pcand,prefix,cand,c1,c2,c3,u,l.strip(),wc,ufeats) 269 | 270 | 271 | 272 | -------------------------------------------------------------------------------- /eval_decompounding.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import re 4 | from operator import add 5 | import operator 6 | if len(sys.argv)<3: 7 | print "cat compound_file | python %s column_predicted column_gold_compound " %(sys.argv[0]) 8 | sys.exit(0) 9 | col_split = int(sys.argv[1]) 10 | col_gold = int(sys.argv[2]) 11 | outp = False 12 | if len(sys.argv)>3: 13 | outp=True 14 | 15 | def getIdx(w): 16 | ws = w.split("-") 17 | i=0 18 | idx = [] 19 | for s in ws: 20 | i+=len(s) 21 | idx.append(i) 22 | return idx 23 | 24 | 25 | def evaluate(w1,w2): 26 | cc=0 #correct splits 27 | wfc = 0 # compound wrong split 28 | wnc = 0 # compound not split 29 | w1i = set(getIdx(w1)) 30 | w2i = set(getIdx(w2)) 31 | cc = len(w1i & w2i) 32 | wnc = len(w1i-w2i) 33 | wfc = len(w2i-w1i) 34 | 35 | return [cc,wfc,wnc] 36 | a=0 37 | c=0 38 | scores=[0,0,0] 39 | for l in sys.stdin: 40 | #if not re.match(col_prefix,l.strip()): 41 | # continue 42 | ls = l.strip().split("\t") 43 | if len(ls)7: 20 | outp=True 21 | 22 | def getIdx(w): 23 | ws = w.split("-") 24 | i=0 25 | idx = [] 26 | for s in ws: 27 | i+=len(s) 28 | idx.append(i) 29 | return idx 30 | 31 | 32 | def evaluate(w1,w2): 33 | cc=0 #correct splits 34 | wfc = 0 # compound wrong split 35 | wnc = 0 # compound not split 36 | w1i = set(getIdx(w1)) 37 | w2i = set(getIdx(w2)) 38 | cc = len(w1i & w2i) 39 | wnc = len(w1i-w2i) 40 | wfc = len(w2i-w1i) 41 | 42 | return [cc,wfc,wnc] 43 | def printEval(scores,a,c): 44 | k = scores 45 | print scores 46 | p = 1.0*k[0]/(1.0*k[0]+k[1]) 47 | r = 1.0*k[0]/(1.0*k[0]+k[1]+k[2]) 48 | f = 2*p*r/(p+r) 49 | sys.stderr.write("%f\t%f\t%f\n"%(p,r,f)) 50 | sys.stderr.write("%f\t%f\t%f\n"%(a,c,1.0*c/a)) 51 | 52 | sys.stderr.write("%10.4f & %10.4f&%10.4f\n"%(p,r,f)) 53 | sys.stderr.write("%f\t%f\t%f\n"%(a,c,1.0*c/a)) 54 | 55 | a1=0 56 | a2=0 57 | c1=0 58 | c2=0 59 | scores1=[0,0,0] 60 | scores2=[0,0,0] 61 | f1_lines = open(f1).readlines() 62 | f2_lines = open(f2).readlines() 63 | if len(f1_lines)!=len(f2_lines): 64 | print "files have not same length" 65 | sys.exit(0) 66 | def computeEvalSc(k): 67 | p = 1.0*k[0]/(1.0*k[0]+k[1]) 68 | r = 1.0*k[0]/(1.0*k[0]+k[1]+k[2]) 69 | if k[0]==0: 70 | f=0.0 71 | else: 72 | f = 2*p*r/(p+r) 73 | return [p,r,f] 74 | x1=[] 75 | x2=[] 76 | xd = [] 77 | mcn = [[0,0],[0,0]] 78 | for i in range(0,len(f1_lines)): 79 | #if not re.match(col_prefix,l.strip()): 80 | # continue 81 | 82 | ls1 = f1_lines[i].strip().split("\t") 83 | ls2 = f2_lines[i].strip().split("\t") 84 | 85 | gold1 = ls1[f1_col_gold].lower() 86 | gold2 = ls2[f2_col_gold].lower() 87 | if gold1 != gold2: 88 | print "inequal: %s\t%s"%(gold1,gold2) 89 | print f1_lines[i].strip() 90 | print f2_lines[i].strip() 91 | cand1 = ls1[f1_col_split].lower() 92 | cand2 = ls2[f2_col_split].lower() 93 | sc1 = evaluate(gold1,cand1) 94 | sc2 = evaluate(gold2,cand2) 95 | e1 = computeEvalSc(sc1) 96 | e2 = computeEvalSc(sc2) 97 | if outp: print "%f\t%f\t%s\t%s\t%s"%(e1[2],e2[2],cand1,cand2,gold1) 98 | x1.append(e1[2]) 99 | x2.append(e2[2]) 100 | xd.append(e2[2]-e1[2]) 101 | scores1=map(add, scores1, sc1) 102 | scores2=map(add, scores2, sc2) 103 | flag1 = "0" 104 | flag2 = "0" 105 | i1 = 0 106 | i2 = 0 107 | if gold2 ==cand2: 108 | flag2 = "1" 109 | c2+=1 110 | i1=1 111 | if gold1 ==cand1: 112 | flag1 = "1" 113 | c1+=1 114 | i2=1 115 | mcn[i1][i2]+=1 116 | if outp : 117 | print flag1+"\t"+f1_lines[i].strip() 118 | print flag2+"\t"+f2_lines[i].strip() 119 | a1+=1 120 | a2+=1 121 | print f1 122 | printEval(scores1,a1,c1) 123 | print f2 124 | printEval(scores2,a2,c2) 125 | #print mcn 126 | #print mcnemar.mcnemar(mcn[0][1],mcn[1][0],mcn[0][0],mcn[1][1],0.05,verbose=True) 127 | #print "test" 128 | #print mcnemar.mcnemar2(mcn[0][1],mcn[1][0],mcn[0][0],mcn[1][1]) 129 | print "Wilcox" 130 | print scipy.stats.wilcoxon(x1, y=x2, zero_method='wilcox') 131 | print scipy.stats.wilcoxon(x2, y=x1, zero_method='wilcox') 132 | print "Wilcox2" 133 | print scipy.stats.wilcoxon(xd, zero_method='wilcox') 134 | #k = scores 135 | #print scores 136 | #p = 1.0*k[0]/(1.0*k[0]+k[1]) 137 | #r = 1.0*k[0]/(1.0*k[0]+k[1]+k[2]) 138 | #f = 2*p*r/(p+r) 139 | #sys.stderr.write("%f\t%f\t%f\n"%(p,r,f)) 140 | #sys.stderr.write("%f\t%f\t%f\n"%(a,c,1.0*c/a)) 141 | # 142 | #sys.stderr.write("%10.4f & %10.4f&%10.4f\n"%(p,r,f)) 143 | #sys.stderr.write("%f\t%f\t%f\n"%(a,c,1.0*c/a)) 144 | -------------------------------------------------------------------------------- /generateDecompoundCandidates.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import re 4 | 5 | dt = {} 6 | i = 0 7 | split_dash = False 8 | acceptRegex=".*" 9 | if len(sys.argv)>1: 10 | acceptRegex = sys.argv[1] 11 | if len(sys.argv)>2: 12 | split_dash = True 13 | accept = re.compile(acceptRegex) 14 | prev = "" 15 | for l in sys.stdin: 16 | ls = l.strip().split("\t") 17 | w1 = ls[0] 18 | w2 = ls[1] 19 | if not (accept.match(w1) and accept.match(w2)): 20 | sys.stderr.write("Not accepted: "+w1+"\t"+w2+"\n") 21 | continue 22 | 23 | 24 | if w1 in dt: 25 | dt[w1].append(w2) 26 | else: 27 | dt[w1]=[w2] 28 | if i%1000000==0: 29 | sys.stderr.write(str(i)+"\n") 30 | i+=1 31 | 32 | def getOverlap(w,ls): 33 | wl = w.lower() 34 | ret = [] 35 | for l in ls: 36 | if l.lower() in wl: 37 | ret.append(l) 38 | if split_dash and "-" in l: 39 | lm = l.split("-") 40 | for m in lm: 41 | if m in wl: 42 | ret.append(l) 43 | return ret 44 | 45 | def addset(d,s): 46 | for w in s: 47 | if w in d: 48 | d[w]+=1 49 | else: 50 | d[w]=1 51 | return d 52 | j = 0 53 | for w1 in dt: 54 | sims = dt[w1] 55 | word_overlap = getOverlap(w1,sims) 56 | sims_overlap = {} 57 | 58 | for w2 in sims: 59 | if w2 in dt: 60 | overlap = getOverlap(w1,dt[w2]) 61 | sims_overlap = addset(sims_overlap,overlap) 62 | out1 = "" 63 | out2 = "" 64 | out3 = " ".join(word_overlap) 65 | for w2 in sims_overlap: 66 | out1+=" " +w2 67 | out2+=" "+w2+":"+str(sims_overlap[w2]) 68 | out3 = out3+out1 69 | out1 = out1.strip() 70 | print w1+"\t"+" ".join(word_overlap)+"\t"+out1+"\t"+out3+"\t"+out2 71 | j+=1 72 | if j%1000000==0: 73 | sys.stderr.write(str(j)+"\t"+str(1.0*j/i)+"\n") 74 | --------------------------------------------------------------------------------