@@ -78,7 +78,7 @@ def __init__(
7878 language = FAILSAFE_LANGUAGE
7979 if newSpellings :
8080 self ._new_spellings = newSpellings
81- self ._register_spellings (self . _new_spellings )
81+ self ._register_spellings ()
8282 self ._language = LanguageTag (language , self ._get_languages ())
8383 self .motherTongue = motherTongue
8484 self .disabled_rules = set ()
@@ -191,33 +191,36 @@ def _get_valid_spelling_file_path() -> str:
191191 .format (spelling_file_path ))
192192 return spelling_file_path
193193
194- def _register_spellings (self , spellings ):
194+ def _register_spellings (self ):
195195 spelling_file_path = self ._get_valid_spelling_file_path ()
196- with (
197- open (spelling_file_path , "a+" , encoding = 'utf-8' )
198- ) as spellings_file :
199- spellings_file .write (
200- "\n " + "\n " .join ([word for word in spellings ])
201- )
196+ with open (spelling_file_path , "r+" , encoding = 'utf-8' ) as spellings_file :
197+ existing_spellings = set (line .strip () for line in spellings_file .readlines ())
198+ new_spellings = [word for word in self ._new_spellings if word not in existing_spellings ]
199+ self ._new_spellings = new_spellings
200+ if new_spellings :
201+ if len (existing_spellings ) > 0 :
202+ spellings_file .write ("\n " )
203+ spellings_file .write ("\n " .join (new_spellings ))
202204 if DEBUG_MODE :
203205 print ("Registered new spellings at {}" .format (spelling_file_path ))
204206
205207 def _unregister_spellings (self ):
206208 spelling_file_path = self ._get_valid_spelling_file_path ()
207- with (
208- open (spelling_file_path , 'r+' , encoding = 'utf-8' )
209- ) as spellings_file :
210- spellings_file .seek (0 , os .SEEK_END )
211- for _ in range (len (self ._new_spellings )):
212- while spellings_file .read (1 ) != '\n ' :
213- spellings_file .seek (spellings_file .tell () - 2 , os .SEEK_SET )
214- spellings_file .seek (spellings_file .tell () - 2 , os .SEEK_SET )
215- spellings_file .seek (spellings_file .tell () + 1 , os .SEEK_SET )
216- spellings_file .truncate ()
209+
210+ with open (spelling_file_path , 'r' , encoding = 'utf-8' ) as spellings_file :
211+ lines = spellings_file .readlines ()
212+
213+ updated_lines = [
214+ line for line in lines if line .strip () not in self ._new_spellings
215+ ]
216+ if updated_lines and updated_lines [- 1 ].endswith ('\n ' ):
217+ updated_lines [- 1 ] = updated_lines [- 1 ].strip ()
218+
219+ with open (spelling_file_path , 'w' , encoding = 'utf-8' , newline = '\n ' ) as spellings_file :
220+ spellings_file .writelines (updated_lines )
221+
217222 if DEBUG_MODE :
218- print (
219- "Unregistered new spellings at {}" .format (spelling_file_path )
220- )
223+ print (f"Unregistered new spellings at { spelling_file_path } " )
221224
222225 def _get_languages (self ) -> set :
223226 """Get supported languages (by querying the server)."""
0 commit comments