• Login
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.
  • C
    Cohenmichael
    last edited by Dec 10, 2019, 4:29 PM

    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

    E 1 Reply Last reply Dec 10, 2019, 4:36 PM Reply Quote 0
    • E
      Ekopalypse @Cohenmichael
      last edited by Dec 10, 2019, 4:36 PM

      @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
      • C
        Cohenmichael
        last edited by Dec 10, 2019, 5:03 PM

        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
        • E
          Ekopalypse
          last edited by Dec 10, 2019, 5:35 PM

          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
          • C
            Cohenmichael
            last edited by Dec 10, 2019, 5:41 PM

            Thanks a lot !

            1 Reply Last reply Reply Quote 0
            • C
              Cohenmichael
              last edited by Dec 11, 2019, 8:48 AM

              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()


              A 1 Reply Last reply Dec 11, 2019, 1:06 PM Reply Quote 0
              • A
                Alan Kilborn @Cohenmichael
                last edited by Dec 11, 2019, 1:06 PM

                @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
                • C
                  Cohenmichael
                  last edited by Dec 11, 2019, 7:12 PM

                  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.

                  A 1 Reply Last reply Dec 11, 2019, 7:15 PM Reply Quote 0
                  • A
                    Alan Kilborn @Cohenmichael
                    last edited by Dec 11, 2019, 7:15 PM

                    @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
                    • C
                      Cohenmichael
                      last edited by Dec 11, 2019, 8:01 PM

                      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()
                      
                      
                      
                      E 1 Reply Last reply Dec 11, 2019, 8:26 PM Reply Quote 0
                      • E
                        Ekopalypse @Cohenmichael
                        last edited by Ekopalypse Dec 11, 2019, 8:28 PM Dec 11, 2019, 8:26 PM

                        @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
                        • C
                          Cohenmichael
                          last edited by Dec 12, 2019, 9:31 AM

                          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.

                          E 1 Reply Last reply Dec 12, 2019, 12:24 PM Reply Quote 1
                          • E
                            Ekopalypse @Cohenmichael
                            last edited by Ekopalypse Dec 12, 2019, 12:24 PM Dec 12, 2019, 12:24 PM

                            @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)
                            
                            C 1 Reply Last reply Dec 12, 2019, 4:26 PM Reply Quote 2
                            • C
                              Cohenmichael @Ekopalypse
                              last edited by Dec 12, 2019, 4:26 PM

                              @Ekopalypse

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

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