new-words

view new-words.py @ 65:5a003076eb11

-w for web support (alpha)
author Igor Chubin <igor@chub.in>
date Tue Mar 27 14:09:25 2012 +0200 (2012-03-27)
parents 1b8b30ad7c95
children 846240941452
line source
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
4 from __future__ import with_statement
5 import codecs
6 import difflib
7 import logging
8 import os
9 import optparse
10 import re
11 import subprocess
12 import sys
13 import Stemmer
14 import tempfile
15 try:
16 import psyco
17 psyco.full()
18 except:
19 pass
21 config = {
22 'config_directory': os.environ['HOME'] + '/.new-words',
23 'language': 'en',
24 }
26 logging.basicConfig(filename='/tmp/new-words-py.log', level=logging.DEBUG)
28 class Normalizator:
29 def __init__(self, language, linked_words={}):
30 stemmer_algorithm = {
31 'de' : 'german',
32 'fr' : 'french',
33 'en' : 'english',
34 'es' : 'spanish',
35 'ru' : 'russian',
36 'it' : 'italian',
37 'uk' : 'ukrainian',
38 }
39 try:
40 self.stemmer = Stemmer.Stemmer(stemmer_algorithm[language])
41 except:
42 self.stemmer = None
43 self.linked_words = linked_words
45 def normalize(self, word):
46 word_chain = []
47 while word in self.linked_words and not word in word_chain:
48 word_chain.append(word)
49 word = self.linked_words[word]
50 if self.stemmer:
51 return self.stemmer.stemWord(word.lower())
52 else:
53 return word.lower()
55 def best_word_from_group(self, wordpairs_group):
56 """Returns the word that is the most relevant to the wordpairs_group.
58 At the moment: returns the word with minimal length"""
60 def f(x, y):
61 return difflib.SequenceMatcher(
62 None,
63 #(x[-2:] == 'en' and x[:-2].lower() or x.lower()),
64 x.lower(),
65 y.lower()).ratio()
67 minimal_length = min(len(pair[1]) for pair in wordpairs_group)
68 best_match = list(x[1] for x in sorted(
69 (x for x in wordpairs_group if len(x[1]) == minimal_length),
70 key=lambda x:x[0],
71 reverse=True))[0]
73 return best_match
75 suggestions = self.dictionary_suggestions(best_match)
76 if len(suggestions) == 1:
77 return best_match
79 verb = False
80 corrected_best_match = best_match
81 if best_match[-2:] == 'et':
82 word = best_match[:-1]+"n"
83 sugg = self.dictionary_suggestions(word)
84 if len(sugg) == 1:
85 return word
86 suggestions += sugg
87 corrected_best_match = word
88 corrected_best_match = best_match[:-2]
89 verb = True
91 if best_match[-1] == 't':
92 word = best_match[:-1]+"en"
93 sugg = self.dictionary_suggestions(word)
94 if len(sugg) == 1:
95 return word
96 suggestions += sugg
97 corrected_best_match = best_match[:-1]
98 verb = True
100 if corrected_best_match[0].lower() == corrected_best_match[0]:
101 suggestions = [ x for x in suggestions
102 if x[0].lower() == x[0] ]
104 if suggestions == []:
105 return best_match+"_"
106 return best_match+" "+(" ".join(
107 sorted(
108 suggestions,
109 key = lambda x: f(x, corrected_best_match),
110 reverse = True
111 )
112 )
113 )
115 def dictionary_suggestions(self, word):
116 return [
117 x.decode('utf-8').rstrip('\n')
118 for x
119 in subprocess.Popen(
120 ["de-variants", word],
121 stdout=subprocess.PIPE
122 ).stdout.readlines() ]
125 parser = optparse.OptionParser()
127 parser.add_option(
128 "-a", "--no-marks",
129 help="don't add marks (and don't save marks added by user) [NOT IMPLEMENTED YET]",
130 action="store_true",
131 dest="no_marks")
133 parser.add_option(
134 "-c", "--compressed",
135 help="show compressed wordlist: one word per group",
136 action="store_true",
137 dest="compressed")
139 parser.add_option(
140 "-k", "--known-words",
141 help="put higher words that are similar to the known words (only for English)",
142 action="store_true",
143 dest="compressed")
145 parser.add_option(
146 "-l", "--language",
147 help="specify language of text",
148 action="store",
149 dest="language")
151 parser.add_option(
152 "-f", "--allowed-words",
153 help="file with list of allowed words (words that will be shown in the output)",
154 action="store",
155 dest="allowed_words")
157 parser.add_option(
158 "-G", "--words-grouping",
159 help="turn off word grouping",
160 action="store_true",
161 dest="no_words_grouping")
163 parser.add_option(
164 "-X", "--function",
165 help="filter through subsystem [INTERNAL]",
166 action="store",
167 dest="function")
169 parser.add_option(
170 "-m", "--merge-tag",
171 help="merge words tagged with specified tag into the main vocabulary [NOT IMPLEMENTED YET]",
172 action="store",
173 dest="merge_tag")
175 parser.add_option(
176 "-M", "--merge-tagged",
177 help="merge words tagged with ANY tag into the main vocabulary [NOT IMPLEMENTED YET]",
178 action="store_true",
179 dest="merge_tagged")
181 parser.add_option(
182 "-n", "--non-interactive",
183 help="non-interactive mode (don't run vi)",
184 action="store_true",
185 dest="non_interactive")
187 parser.add_option(
188 "-N", "--no-filter",
189 help="switch off known words filtering",
190 action="store_true",
191 dest="no_filter")
193 parser.add_option(
194 "-p", "--pages",
195 help="work with specified pages only (pages = start-stop/total )",
196 action="store",
197 dest="pages")
199 parser.add_option(
200 "-d", "--delete-tag",
201 help="delete subvocabulary of specified tag",
202 action="store",
203 dest="delete_tag")
205 parser.add_option(
206 "-r", "--show-range",
207 help="show only words specified number of words",
208 action="store",
209 dest="show_range")
211 parser.add_option(
212 "-R", "--show-range-percentage",
213 help="show only words that cover specified percentage of the text, skip the rest",
214 action="store",
215 dest="show_range_percentage")
217 parser.add_option(
218 "-s", "--text-stats",
219 help="show the text statistics (percentage of known words and so on) and exit",
220 action="store_true",
221 dest="text_stats")
223 parser.add_option(
224 "-S", "--voc-stats",
225 help="show your vocabulary statistics (number of words and word groups) [NOT IMPLEMENTED YET]",
226 action="store_true",
227 dest="voc_stats")
229 parser.add_option(
230 "-t", "--tag",
231 help="tag known words with tag",
232 action="store",
233 dest="tag")
235 parser.add_option(
236 "-T", "--show-tags",
237 help="tag known words with tag",
238 action="store_true",
239 dest="show_tags")
241 parser.add_option(
242 "-v", "--vocabulary-filename",
243 help="use specified file as a vocabulary",
244 action="store",
245 dest="vocabulary_filename")
247 parser.add_option(
248 "-w", "--web",
249 help="Web browser version",
250 action="store_true",
251 dest="web")
253 parser.add_option(
254 "-2", "--two-words",
255 help="find 2 words' sequences",
256 action="store_true",
257 dest="two_words")
259 parser.add_option(
260 "-3", "--three-words",
261 help="find 3 words' sequences",
262 action="store_true",
263 dest="three_words")
265 def readlines_from_file(filename):
266 res = []
267 with codecs.open(filename, "r", "utf-8") as f:
268 for line in f.readlines():
269 res += [line]
270 return res
272 def readlines_from_url(url):
273 return [x.decode('utf-8') for x in
274 subprocess.Popen(
275 "lynx -dump '{url}' | perl -p -e 's@http://[a-zA-Z&_.:/0-9%?=,#+()\[\]~-]*@@'".format(url=url),
276 shell = True,
277 stdout = subprocess.PIPE,
278 stderr = subprocess.STDOUT
279 ).communicate()[0].split('\n')
280 ]
282 def readlines_from_stdin():
283 return codecs.getreader("utf-8")(sys.stdin).readlines()
285 def words_from_line(line):
286 line = line.rstrip('\n')
287 #return re.split('(?:\s|[*\r,.:#@()+=<>$;"?!|\[\]^%&~{}«»–])+', line)
288 #return re.split('[^a-zA-ZäöëüßÄËÖÜß]+', line)
289 return re.compile("(?!['_])(?:\W)+", flags=re.UNICODE).split(line)
291 def get_words(lines, group_by=[1]):
292 """
293 Returns hash of words in a file
294 word => number
295 """
296 result = {}
297 (a, b, c) = ("", "", "")
298 for line in lines:
299 words = words_from_line(line)
300 for word in words:
301 if re.match('[0-9]*$', word):
302 continue
303 result.setdefault(word, 0)
304 result[word] += 1
305 if 2 in group_by and a != "" and b != "":
306 w = "%s_%s" % (a,b)
307 result.setdefault(w, 0)
308 result[w] += 1
309 if 3 in group_by and not "" in [a,b,c]:
310 w = "%s_%s_%s" % (a,b,c)
311 result.setdefault(w, 0)
312 result[w] += 1
313 (a,b,c) = (b, c, word)
315 logging.debug(result)
316 return result
318 def voc_filename():
319 if 'vocabulary_filename' in config:
320 return config['vocabulary_filename']
321 return "%s/%s.txt"%(config['config_directory'], config['language'])
323 def load_vocabulary():
324 return get_words(readlines_from_file(voc_filename()))
326 def notes_filenames():
327 return ["%s/notes-%s.txt"%(config['config_directory'], config['language'])]
329 def load_notes(files):
330 notes = {}
331 for filename in files:
332 with codecs.open(filename, "r", "utf-8") as f:
333 for line in f.readlines():
334 (word, note) = re.split('\s+', line.rstrip('\n'), maxsplit=1)
335 notes.setdefault(word, {})
336 notes[word][filename] = note
337 return notes
339 def add_notes(lines, notes):
340 notes_filename = notes_filenames()[0]
341 result = []
342 for line in lines:
343 if line.startswith('#'):
344 result += [line]
345 else:
346 match_object = re.search('^\s*\S+\s*(\S+)', line)
347 if match_object:
348 word = match_object.group(1)
349 if word in notes:
350 if notes_filename in notes[word]:
351 line = line.rstrip('\n')
352 line = "%-30s %s\n" % (line, notes[word][notes_filename])
353 result += [line]
354 else:
355 result += [line]
356 else:
357 result += [line]
358 return result
360 def remove_notes(lines, notes_group):
361 notes_filename = notes_filenames()[0]
362 notes = {}
363 for k in notes_group.keys():
364 if notes_filename in notes_group[k]:
365 notes[k] = notes_group[k][notes_filename]
367 result = []
368 for line in lines:
369 line = line.rstrip('\n')
370 match_object = re.match('(\s+)(\S+)(\s+)(\S+)(\s+)(.*)', line)
371 if match_object:
372 result.append("".join([
373 match_object.group(1),
374 match_object.group(2),
375 match_object.group(3),
376 match_object.group(4),
377 "\n"
378 ]))
379 notes[match_object.group(4)] = match_object.group(6)
380 else:
381 result.append(line+"\n")
383 save_notes(notes_filename, notes)
384 return result
386 def save_notes(filename, notes):
387 lines = []
388 saved_words = []
389 with codecs.open(filename, "r", "utf-8") as f:
390 for line in f.readlines():
391 (word, note) = re.split('\s+', line.rstrip('\n'), maxsplit=1)
392 if word in notes:
393 line = "%-29s %s\n" % (word, notes[word])
394 saved_words.append(word)
395 lines.append(line)
396 for word in [x for x in notes.keys() if not x in saved_words]:
397 line = "%-29s %s\n" % (word, notes[word])
398 lines.append(line)
400 with codecs.open(filename, "w", "utf-8") as f:
401 for line in lines:
402 f.write(line)
405 def substract_dictionary(dict1, dict2):
406 """
407 returns dict1 - dict2
408 """
409 result = {}
410 for (k,v) in dict1.items():
411 if not k in dict2:
412 result[k] = v
413 return result
415 def dump_words(words, filename):
416 with codecs.open(filename, "w+", "utf-8") as f:
417 for word in words.keys():
418 f.write(("%s\n"%word)*words[word])
420 def error_message(text):
421 print text
423 def find_wordgroups_weights(word_pairs, normalizator):
424 weight = {}
425 for (num, word) in word_pairs:
426 normalized = normalizator.normalize(word)
427 weight.setdefault(normalized, 0)
428 weight[normalized] += num
429 return weight
431 def find_linked_words(notes):
432 linked_words = {}
433 for word in notes.keys():
434 for note in notes[word].values():
435 if "@" in note:
436 result = re.search(r'\@(\S*)', note)
437 if result:
438 main_word = result.group(1)
439 if main_word:
440 linked_words[word] = main_word
441 return linked_words
443 def compare_word_pairs(pair1, pair2, wgw, normalizator, linked_words):
444 (num1, word1) = pair1
445 (num2, word2) = pair2
447 normalized_word1 = normalizator.normalize(word1)
448 normalized_word2 = normalizator.normalize(word2)
450 cmp_res = cmp(wgw[normalized_word1], wgw[normalized_word2])
451 if cmp_res != 0:
452 return cmp_res
453 else:
454 cmp_res = cmp(normalized_word1, normalized_word2)
455 if cmp_res != 0:
456 return cmp_res
457 else:
458 return cmp(int(num1), int(num2))
461 def print_words_sorted(
462 word_pairs,
463 stats,
464 normalizator,
465 print_stats=True,
466 stats_only=False,
467 compressed_wordlist=False,
468 show_range=0,
469 show_range_percentage=0,
470 ):
471 result = []
472 if stats_only:
473 #codecs.getwriter("utf-8")(sys.stdout).write(
474 result.append(
475 " ".join([
476 "%-10s" % x for x in [
477 "LANG",
478 "KNOWN%",
479 "UNKNOWN%",
480 "KNOWN",
481 "TOTAL",
482 "WPS",
483 "UWPS*10"
484 ]]) + "\n")
485 result.append(
486 " ".join([
487 "%(language)-10s",
488 "%(percentage)-10.2f",
489 "%(percentage_unknown)-10.2f",
490 "%(total_known)-11d"
491 "%(total)-11d"
492 "%(wps)-11d"
493 "%(uwps)-11d"
494 ]) % stats + "\n")
495 return "".join(result)
497 if print_stats:
498 result.append(
499 "# %(language)s, %(percentage)-7.2f, <%(total_known)s/%(total)s>, <%(groups)s/%(words)s>\n" % stats)
501 level_lines = range(int(float(stats['percentage']))/5*5+5,95,5)+range(90,102)
502 known = int(stats['total_known'])
503 total = int(stats['total'])
504 current_level = 0
505 old_normalized_word = None
506 words_of_this_group = []
507 printed_words = 0
508 for word_pair in word_pairs:
510 normalized_word = normalizator.normalize(word_pair[1])
511 if old_normalized_word and old_normalized_word != normalized_word:
512 if compressed_wordlist:
513 compressed_word_pair = (
514 sum(x[0] for x in words_of_this_group),
515 normalizator.best_word_from_group(words_of_this_group)
516 )
517 result.append("%10s %s\n" % compressed_word_pair)
518 printed_words += 1
519 words_of_this_group = []
521 old_normalized_word = normalized_word
522 words_of_this_group.append(word_pair)
524 if not compressed_wordlist:
525 result.append("%10s %s\n" % word_pair)
526 printed_words += 1
529 known += word_pair[0]
530 if 100.0*known/total >= level_lines[0]:
531 current_level = level_lines[0]
532 while 100.0*known/total > level_lines[0]:
533 current_level = level_lines[0]
534 level_lines = level_lines[1:]
535 result.append("# %s\n" % current_level)
537 if show_range >0 and printed_words >= show_range:
538 break
539 if show_range_percentage >0 and 100.0*known/total >= show_range_percentage:
540 break
542 return result
544 def parse_parts_description(parts_description):
545 """
546 Returns triad (start, stop, step)
547 basing on parts_description string.
548 from-to/step
549 from+delta/step
550 """
552 try:
553 (a, step) = parts_description.split("/", 1)
554 step = int(step)
555 start = 0
556 stop = 0
557 if '-' in a:
558 (start, stop) = a.split("-", 1)
559 start = int(start)
560 stop = int(stop)
561 elif '+' in a:
562 (start, stop) = a.split("+", 1)
563 start = int(start)
564 stop = int(stop)
565 else:
566 start = int(a)
567 stop = start + 1
568 return (start, stop, step)
570 except:
571 raise ValueError("Parts description must be in format: num[[+-]num]/num; this [%s] is incorrect" % parts_description)
574 def take_part(lines, part_description = None):
575 if part_description == None or part_description == '':
576 return lines
577 (start, stop, step) = parse_parts_description(part_description)
578 n = len(lines)
579 part_size = (1.0*n) / step
580 result = []
581 for i in range(n):
582 if i >= start * part_size and i <= stop * part_size:
583 result += [lines[i]]
584 return result
586 def web_editor(output):
587 from twisted.internet import reactor
588 from twisted.web.server import Site
589 from twisted.web.static import File
590 from twisted.web.resource import Resource
591 import json
593 word_list = []
595 for o in output:
596 a = re.split('\s+', o.strip(), 2)
597 a = a + ['']*(3-len(a))
598 word_list.append({'number':a[0], 'word':a[1], 'comment':a[2]})
600 print "Loaded ", len(word_list)
602 new_words_html = "/home/igor/hg/new-words/web"
604 class JSONPage(Resource):
605 isLeaf = True
606 def render_GET(self, request):
607 return json.dumps({"word_list": word_list})
609 class SaveJSON(Resource):
610 isLeaf = True
611 def render_POST(self, request):
612 print json.loads(request.args["selected_words"][0])
613 return json.dumps({"status": "ok"})
615 json_page = JSONPage()
616 save_json = SaveJSON()
618 resource = File(new_words_html)
619 resource.putChild("json", json_page)
620 resource.putChild("save", save_json)
622 factory = Site(resource)
623 reactor.listenTCP(8880, factory)
624 reactor.run()
627 def filter_get_words_group_words_add_stat(args):
628 vocabulary = load_vocabulary()
629 notes = load_notes(notes_filenames())
631 input_lines = []
632 if len(args) > 0:
633 for arg in args:
634 if 'http://' in arg:
635 input_lines += readlines_from_url(arg)
636 else:
637 input_lines += readlines_from_file(arg)
638 else:
639 input_lines += readlines_from_stdin()
641 if len(input_lines) == 0:
642 print >> sys.stderr, "Nothing to do, standard input is empty, exiting."
643 sys.exit(1)
645 lines = take_part(input_lines, config.get('pages', ''))
647 (_, original_text_tempfile) = tempfile.mkstemp(prefix='new-word')
648 with codecs.open(original_text_tempfile, "w", "utf-8") as f:
649 f.write("".join(lines))
651 group_by = [1]
653 if 'two_words' in config:
654 group_by.append(2)
655 if 'three_words' in config:
656 group_by.append(3)
657 words = get_words(lines, group_by)
658 stats_only = False
659 if 'text_stats' in config:
660 stats_only = True
662 compressed_wordlist = False
663 if 'compressed' in config:
664 compressed_wordlist = True
666 if 'show_range' in config:
667 show_range = int(config['show_range'])
668 else:
669 show_range = 0
671 if 'show_range_percentage' in config:
672 show_range_percentage = int(config['show_range_percentage'])
673 else:
674 show_range_percentage = 0
677 stats = {}
678 stats['total'] = sum(words[x] for x in words.keys())
679 if not 'no_filter' in config:
680 words = substract_dictionary(words, vocabulary)
682 stats['total_unknown'] = sum(words[x] for x in words.keys())
683 stats['total_known'] = stats['total'] - stats['total_unknown']
684 stats['percentage'] = 100.0*stats['total_known']/stats['total']
685 stats['percentage_unknown'] = 100.0-100.0*stats['total_known']/stats['total']
686 stats['groups'] = 0
687 stats['words'] = len(words)
688 stats['sentences'] = 0 #FIXME
689 stats['wps'] = 0 #FIXME
690 stats['uwps'] = 0 #FIXME
691 stats['language'] = config['language']
693 linked_words = find_linked_words(notes)
694 normalizator = Normalizator(config['language'], linked_words)
696 # filter words by allowed_words_filter
697 if 'allowed_words' in config:
698 allowed_words_filename = config['allowed_words']
699 normalized_allowed_words = [
700 normalizator.normalize(w.rstrip('\n'))
701 for w in readlines_from_file(allowed_words_filename)
702 ]
704 result = {}
705 for w, wn in words.iteritems():
706 if normalizator.normalize(w) in normalized_allowed_words:
707 result[w] = wn
708 words = result
710 words_with_freq = []
711 for k in sorted(words.keys(), key=lambda k: words[k], reverse=True):
712 words_with_freq.append((words[k], k))
714 wgw = find_wordgroups_weights(words_with_freq, normalizator)
715 if not 'no_words_grouping' in config or not config['no_words_grouping']:
716 words_with_freq = sorted(
717 words_with_freq,
718 cmp=lambda x,y:compare_word_pairs(x,y, wgw, normalizator, linked_words),
719 reverse=True)
721 output = print_words_sorted(
722 words_with_freq,
723 stats,
724 normalizator,
725 stats_only=stats_only,
726 compressed_wordlist=compressed_wordlist,
727 show_range=show_range,
728 show_range_percentage=show_range_percentage,
729 )
732 if ('non_interactive' in config or 'text_stats' in config):
733 codecs.getwriter("utf-8")(sys.stdout).write("".join(output))
734 elif config.get('web', False):
735 web_editor(output)
736 else:
737 (_, temp1) = tempfile.mkstemp(prefix='new-word')
738 (_, temp2) = tempfile.mkstemp(prefix='new-word')
740 with codecs.open(temp1, "w", "utf-8") as f:
741 f.write("".join(output))
742 with codecs.open(temp2, "w", "utf-8") as f:
743 f.write("".join(add_notes(output, notes)))
745 os.putenv('ORIGINAL_TEXT', original_text_tempfile)
746 os.system((
747 "vim"
748 " -c 'setlocal spell spelllang={language}'"
749 " -c 'set keywordprg={language}'"
750 " -c 'set iskeyword=@,48-57,/,.,-,_,+,,,#,$,%,~,=,48-255'"
751 " {filename}"
752 " < /dev/tty > /dev/tty"
753 ).format(language=config['language'], filename=temp2))
755 lines = remove_notes(readlines_from_file(temp2), notes)
757 # compare lines_before and lines_after and return deleted words
758 lines_before = output
759 lines_after = lines
760 deleted_words = []
762 lines_after_set = set(lines_after)
763 for line in lines_before:
764 if line not in lines_after_set:
765 line = line.strip()
766 if ' ' in line:
767 word = re.split('\s+', line, 1)[1]
768 if ' ' in word:
769 word = re.split('\s+', word, 1)[0]
770 deleted_words.append(word)
772 with codecs.open(voc_filename(), "a", "utf-8") as f:
773 f.write("\n".join(deleted_words + ['']))
775 os.unlink(temp1)
776 os.unlink(temp2)
778 os.unlink(original_text_tempfile)
780 (options, args) = parser.parse_args()
781 if options.language:
782 config['language'] = options.language
784 if options.pages:
785 config['pages'] = options.pages
786 else:
787 config['pages'] = ""
789 if options.allowed_words:
790 config['allowed_words'] = options.allowed_words
792 if options.show_range:
793 config['show_range'] = options.show_range
795 if options.show_range_percentage:
796 config['show_range_percentage'] = options.show_range_percentage
798 if options.non_interactive:
799 config['non_interactive'] = True
801 if options.text_stats:
802 config['text_stats'] = True
804 if options.compressed:
805 config['compressed'] = True
807 if options.no_filter:
808 config['no_filter'] = True
810 if options.two_words:
811 config['two_words'] = True
813 if options.three_words:
814 config['three_words'] = True
816 if options.no_words_grouping:
817 config['no_words_grouping'] = True
819 if options.web:
820 config['web'] = True
822 filter_get_words_group_words_add_stat(args)
824 #if options.function:
825 # function_names = {
826 # 'get_words_group_words_add_stat': ,
827 # }
828 # if options.function in function_names:
829 # function_names[options.function](args)
830 # else:
831 # error_message("Unkown function %s.\nAvailable functions:\n%s" % (
832 # options.function, "".join([" "+x for x in sorted(function_names.keys())])))
833 # sys.exit(1)
834 #
838 #os.system("vim")