Community
    • Login

    Add number in each word by Notepad++

    Scheduled Pinned Locked Moved Help wanted · · · – – – · · ·
    23 Posts 3 Posters 2.1k Views
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • CohenmichaelC
      Cohenmichael
      last edited by

      Thanks a lot !

      1 Reply Last reply Reply Quote 0
      • CohenmichaelC
        Cohenmichael
        last edited by

        Hi,

        I did a search on google, and I made a small modification on the script.

        Notepad ++ opens all the pages of the folder, and the change is made only to the last document.txt and the rest is intact.

        thank you

        -----------The script------------

        import os

        os.chdir(‘C:\Users\yrkj\Desktop\allfiles’)
        list_of_files = [x for x in os.listdir(‘.’) if x.endswith(‘.txt’)]
        for file in list_of_files:
        notepad.open(file)

        from Npp import editor

        def add_number(line_content, line_number, total_num_lines):
        words = line_content.split(’ ')
        for i, word in enumerate(words):
        if word == ‘hello’:
        words[i] = ‘{}.{}’.format(i, word)
        editor.replaceWholeLine(line_number, ’ '.join(words))
        notepad.getFiles()
        editor.forEachLine(add_number)

        notepad.save()
        notepad.close()


        Alan KilbornA 1 Reply Last reply Reply Quote 0
        • Alan KilbornA
          Alan Kilborn @Cohenmichael
          last edited by

          @Cohenmichael

          Put your script in a code block using the </> “toolbar button” when composing. Python relies on indentation when defining blocks, so it is impossible to tell the true logic of your script the way you posted it.

          1 Reply Last reply Reply Quote 1
          • CohenmichaelC
            Cohenmichael
            last edited by

            I don’t know how to do that !
            I don’t have any knowledge about programming scripts for Python, I just tried if it work but it didn’t work.
            The published script is targeted only for Ekopalypse, maybe it has ideas to make it work.

            Alan KilbornA 1 Reply Last reply Reply Quote 0
            • Alan KilbornA
              Alan Kilborn @Cohenmichael
              last edited by

              @Cohenmichael said in Add number in each word by Notepad++:

              I don’t know how to do that !

              You don’t know how to select some text in a post you are composing and press this button??:

              4be83515-c510-4ae0-bb3d-d374be8be5d4-image.png
              Ye Gods, Man!

              1 Reply Last reply Reply Quote 0
              • CohenmichaelC
                Cohenmichael
                last edited by

                Sorry, I misunderstood your message.

                from Npp import editor
                
                def add_number(line_content, line_number, total_num_lines):
                    words = line_content.split(' ')
                    for i, word in enumerate(words):
                        if word == 'nounous':
                            words[i] = '{}.{}'.format(i, word)
                    editor.replaceWholeLine(line_number, ' '.join(words))
                
                editor.forEachLine(add_number)
                notepad.getFiles()
                
                
                
                EkopalypseE 1 Reply Last reply Reply Quote 0
                • EkopalypseE
                  Ekopalypse @Cohenmichael
                  last edited by Ekopalypse

                  @Cohenmichael

                  do you see a need to open each file in notepad,
                  using editor instance to manipulate it
                  and then using notepad instance to save and close it?
                  It could be done with plain file read/write as well.

                  Test the script extensively before using it in production

                  Assumptions done by the following script is
                  Folder as workspace is visible
                  The word looking for is exactly Hello, not hello or HELLO …
                  Only the root directory is scanned for files having .txt extension, no recursion aka subdirectories are searched.

                  import os
                  import ctypes
                  from ctypes import wintypes
                  
                  user32 = ctypes.WinDLL('user32', use_last_error=True)
                  
                  PINT = ctypes.POINTER(wintypes.INT)
                  EnumWindowsProc = ctypes.WINFUNCTYPE(wintypes.BOOL,
                                                       PINT,
                                                       PINT)
                  
                  SendMessage = user32.SendMessageW
                  SendMessage.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
                  SendMessage.restype  = wintypes.LPARAM
                  
                  class TVITEM(ctypes.Structure):
                      _fields_ = [("mask",            wintypes.UINT),
                                  ("hitem",           wintypes.HANDLE),
                                  ("state",           wintypes.UINT),
                                  ("stateMask",       wintypes.UINT),
                                  ("pszText",         wintypes.LPCWSTR),
                                  ("cchTextMax",      wintypes.INT),
                                  ("iImage",          wintypes.INT),
                                  ("iSelectedImage",  wintypes.INT),
                                  ("cChildren",       wintypes.INT),
                                  ("lparam",          ctypes.POINTER(wintypes.LPARAM)),]
                                  
                  TV_FIRST = 0x1100
                  TVM_GETNEXTITEM, TVM_GETITEMW = TV_FIRST+10, TV_FIRST+62
                  TVGN_ROOT, TVGN_NEXT  = 0, 1
                  TVIF_PARAM = 4
                  
                  
                  window_handles = dict()
                  
                  
                  def add_number(path):
                      ''' Generates a list of files which end with .txt
                          for the given directory (no recursion).
                          For each file read the content and add an
                          increasing number, per line, for each
                          occurance of word Hello
                      '''
                      list_of_files = [x for x in os.listdir(path) if x.endswith('.txt')]
                      for file in list_of_files:
                          print(file)
                          new_content = ''
                          file = os.path.join(path, file)
                          with open(file, 'r') as f:
                              for line in f.readlines():
                                  words = line.split(' ')
                                  j = 0
                                  for i, word in enumerate(words):
                                      if word.strip() == 'Hello':
                                          j += 1
                                          words[i] = '{}.{}'.format(j, word)
                                  new_content += ' '.join(words)
                                  
                          with open(file, 'w') as f:
                              f.write(new_content)
                  
                  
                  def enumerate_root_nodes(h_systreeview32):
                      ''' Returns a list of all root nodes from a given treeview handle '''
                      root_nodes = []
                      hNode = user32.SendMessageW(h_systreeview32,
                                                  TVM_GETNEXTITEM,
                                                  TVGN_ROOT,
                                                  0)
                      while hNode:
                          root_nodes.append(hNode)
                          hNode = user32.SendMessageW(h_systreeview32,
                                                      TVM_GETNEXTITEM,
                                                      TVGN_NEXT,
                                                      hNode)
                      return root_nodes
                  
                      
                  def foreach_window(hwnd, lParam):
                      ''' Look for the Workspace as folder dialog
                          and find the treeview handle
                      '''
                      if user32.IsWindowVisible(hwnd):
                          length = user32.GetWindowTextLengthW(hwnd) + 1
                          buffer = ctypes.create_unicode_buffer(length)
                          user32.GetWindowTextW(hwnd, buffer, length)
                  
                          if buffer.value == u'File Browser':
                              h_systreeview32 = user32.FindWindowExW(hwnd, None, u'SysTreeView32', None)
                  
                              if h_systreeview32:
                                  window_handles['file_browser_treeview'] = h_systreeview32
                              return False
                      return True
                  
                  
                  hwnd = user32.FindWindowW(u'Notepad++', None)
                  user32.EnumChildWindows(hwnd, EnumWindowsProc(foreach_window), 0)
                  
                  if 'file_browser_treeview' in window_handles:
                      root_nodes = enumerate_root_nodes(window_handles['file_browser_treeview'])
                  
                      tvitem = TVITEM()
                      tvitem.mask = TVIF_PARAM
                      for root_node in root_nodes:
                          tvitem.hitem = root_node
                          user32.SendMessageW(h_systreeview32, TVM_GETITEMW, 0, ctypes.addressof(tvitem))
                          path = ctypes.wstring_at(tvitem.lparam.contents.value)
                          if path:
                              add_number(path)
                  

                  UPDATE: open the python script console to see which file gets manipulated

                  1 Reply Last reply Reply Quote 2
                  • CohenmichaelC
                    Cohenmichael
                    last edited by

                    I tried 2 operations and the script didn’t work.

                    1st operation: I opened the folder content all documents (.txt) by Folder as WorkSpace, then I clicked execute the script and displayed this message:

                    Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:22:17) [MSC v.1500 32 bit (Intel)]
                    Initialisation took 31ms
                    Ready.
                    Traceback (most recent call last):
                      File "C:\Users\yrkj\AppData\Roaming\Notepad++\plugins\Config\PythonScript\scripts\Hello.py", line 107, in <module>
                        user32.SendMessageW(h_systreeview32, TVM_GETITEMW, 0, ctypes.addressof(tvitem))
                    NameError: name 'h_systreeview32' is not defined
                    

                    2nd operation :
                    I opened all documents (.txt) on Notepad++ and I ran the script, no change on all pages, and it didn’t display any message.

                    EkopalypseE 1 Reply Last reply Reply Quote 1
                    • EkopalypseE
                      Ekopalypse @Cohenmichael
                      last edited by Ekopalypse

                      @Cohenmichael

                      I see, not at my computer but I think if you change this lines it should work.

                      if 'file_browser_treeview' in window_handles:
                          h_systreeview32 = window_handles['file_browser_treeview']
                          root_nodes = enumerate_root_nodes(h_systreeview32)
                      
                      CohenmichaelC 1 Reply Last reply Reply Quote 2
                      • CohenmichaelC
                        Cohenmichael @Ekopalypse
                        last edited by

                        @Ekopalypse

                        Thank you so much. The script works very well !
                        Thanks again for your precious help :)

                        1 Reply Last reply Reply Quote 2
                        • First post
                          Last post
                        The Community of users of the Notepad++ text editor.
                        Powered by NodeBB | Contributors