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.
    • EkopalypseE
      Ekopalypse @Cohenmichael
      last edited by

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

      Is it possible with Notepad++ ?

      I tend to say no. Regex, normally, does not have a way to do
      mathematical operations. From my point of view you need a scripting
      language like PythonScript/LuaScript to do such operations.
      If you want to go this way, let us know.

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

        Thanks for your help.
        What are the steps to follow for PythonScript?

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

          This depends on which npp version you are using.
          Can you post your debug info which is available from ? menu, the last menu item?
          Or do you already have pythonscript installed?

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

            Hi,

            I just installed PythonScript on Notepad++ 7.6.4, 32 bit. It’s functional now !

            What is the script to set up ?

            Many thanks,

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

              Version of PythonScript 1.3!

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

                @Cohenmichael

                What is the script to set up ?

                Depends on your exact requirements.
                Do you want to add a number on any word or just on hello?
                A script might look like this.

                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[0].isalpha():
                            words[i] = '{}.{}'.format(i, word)
                    editor.replaceWholeLine(line_number, ' '.join(words))
                
                editor.forEachLine(add_number)
                

                Steps to do:
                Plugins->PythonScript->New Script
                give it a meaningful name
                copy and save script
                Plugins->PythonScript->Configuration
                put it into menu or toolbar
                done

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

                  Thank you so much. It works well !

                  I want the script only for the word Hello.

                  I have several pages that contains this keyword, is it possible to make it automatic on all pages ?

                  Thanks again,

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

                    @Cohenmichael

                    so you would change, if not already done, to

                    if word == 'Hello':
                    

                    is it possible to make it automatic on all pages

                    Means what?
                    You have all pages open in npp in different tabs?
                    Is a bunch of files in a directory?
                    Should be done when opening a file automatically?
                    You wanna execute a script which runs through the directory
                    and replaces it in each file when found?
                    Something else?

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

                      I made the change. The script is functional!

                      I have several files (.txt) in a folder. I could not execute the script automatically on all pages. Manually it works obviously!

                      How to run the script automatically on all pages?

                      Thanks a lot for your help

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

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

                        automatically

                        You need to explain what automatically in your case means.
                        There must be trigger to run the script but for which trigger
                        are you looking for?
                        Could you explain what you want to do? Like,
                        if I start npp and open file x I want to have result y
                        or
                        if I start the pc I want to have my coffee machine making me coffee
                        …
                        Do you get what I’m looking for?

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

                          Sorry if I was not clear.

                          I want to make a modification on all the words “Hello” existing on all pages name1.txt, name2.txt, … +100 document.txt

                          When I use Notepad ++, I open my folder contains all documents (.txt) by Folder as WorkSpace.

                          In this step, I don’t know what to do to change the word “Hello” on all pages automatically with this script.

                          1 Reply Last reply Reply Quote 0
                          • EkopalypseE
                            Ekopalypse
                            last edited by

                            Ok I see - not that easy - let me think about it.
                            As I’m leaving the office now I’m following up on this later this day,
                            unless someone else jumped in and provided a solution with fits your need.

                            1 Reply Last reply Reply Quote 1
                            • 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
                                            • First post
                                              Last post
                                            The Community of users of the Notepad++ text editor.
                                            Powered by NodeBB | Contributors