Jump to content
Luigi

Translate PYTHON's code to AUTOIT

Recommended Posts

Greetings,
 

Someone can help-me to translate this Python's code to AutoIt?

 

Python (source: https://repl.it/repls/InstructiveDarkslategreyJackrabbit)

str = 'age=12,name=bob,hobbies="games,reading",phrase="I\'m cool!"'
key = ""
val = ""
dict = {}
parse_string = False
parse_key = True
# parse_val = False
for c in str:
    print(c)
    if c == '"' and not parse_string:
        parse_string = True
        continue
    elif c == '"' and parse_string:
        parse_string = False
        continue
    if parse_string:
        val += c
        continue
    if c == ',': # terminate entry
        dict[key] = val #add to dict
        key = ""
        val = ""
        parse_key = True
        continue
    elif c == '=' and parse_key:
        parse_key = False
    elif parse_key:
        key += c
    else:
        val+=c
dict[key] = val
print(dict.items())

Python's output:

[('phrase', "I'm cool!"), ('age', '12'), ('name', 'bob'), ('hobbies', 'games,reading')]

AutoIt

#include-once
#include <Array.au3>
#include <StringConstants.au3>


Global $opt
$opt = "estado = """" , cep = """", idade=32, nome = ""Luismar"", campo=""campo = campo"""
$opt = "age=12,name=bob,hobbies=""games,reading"",phrase=""I\'m cool!"""
ConsoleWrite($opt & @LF)

Local $arr = StringSplit($opt, "", $STR_CHRSPLIT)

Local $key = ""
Local $val = ""
Local $dict = ObjCreate("Scripting.Dictionary")
Local $parse_string = False
Local $parse_key = True
Local $c


For $ii = 1 To $arr[0]
    $c = $arr[$ii]
    If $c == '"' And Not $parse_string Then
        $parse_string = True
        ContinueLoop
    ElseIf $c == """" And $parse_string Then
        $parse_string = False
        ContinueLoop
    EndIf

    If $parse_string Then
        $val &= $c
        ContinueLoop
    EndIf

    If $c = "," Then
        $dict.Add($key, $val)
        $key = ""
        $val = ""
        $parse_key = True
        ContinueLoop
    ElseIf $c == "=" And $parse_key Then
        $parse_key = False
    ElseIf $parse_key Then
        $key &= $c
    Else
        $val &= $c
    EndIf
Next
$dict.Add($key, $val) ; missing this line...

For $each In $dict
    ConsoleWrite($each & " = " & $dict.Item($each) & @LF)
Next

AutoIt's output

age=12,name=bob,hobbies="games,reading",phrase="I\'m cool!"
age = 12
name = bob
hobbies = games,reading

 

Best regards.

 

Edited by Luigi

Share this post


Link to post
Share on other sites

One of the large number of ways to achieve that parsing:

Local $opt1 = 'estado = "" , cep = "", idade=32, nome = "Luismar", campo="campo = campo"'
Local $opt2 = 'age=12,name=bob,hobbies="games,reading",phrase="I''m cool!"'

Local $s
$s = StringRegExp($opt1, '(?m)([^=]+?) ?= ?(?|"([^"]*?)"|([^,]*?)) ?(?:,|$)', 3)
_ArrayDisplay($s)
$s = StringRegExp($opt2, '(?m)([^=]+?) ?= ?(?|"([^"]*?)"|([^,]*?)) ?(?:,|$)', 3)
_ArrayDisplay($s)

If you actually need a {key, value} scripting dictionary from the result, build one from the output array.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

You may have to slightly adapt the pattern if there are different spacings between elements parts.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By b9k
      Hi, I am stuck on a GUI problem and would like your help to solve it.
      I am trying to automate the SoundWire Server app to match my current system volume level while it is minimized to the notification area (so no clicking or stealing focus),
      I can already get the handle and alter the tracker position by sending a WM_SETPOS message, but somehow the actual volume is not changed: I think I need to do something else to trigger the event handler for the value change and propagate it correctly.
      This is the control summary from Au3 info:
      >>>> Window <<<< Title: SoundWire Server Class: #32770 Position: 441, 218 Size: 566, 429 Style: 0x94CA00C4 ExStyle: 0x00050101 Handle: 0x0000000000510E12 >>>> Control <<<< Class: msctls_trackbar32 Instance: 4 ClassnameNN: msctls_trackbar324 Name: Advanced (Class): [CLASS:msctls_trackbar32; INSTANCE:4] ID: 6002 Text: Position: 51, 222 Size: 47, 126 ControlClick Coords: 1, 101 Style: 0x5001000A ExStyle: 0x00000000 Handle: 0x00000000001234C8 >>>> Mouse <<<< Position: 496, 567 Cursor ID: 2 Color: 0xF0F0F0 >>>> StatusBar <<<< >>>> ToolsBar <<<< >>>> Visible Text <<<< Default multimedia device Tray on Start Static Server Address: 192.168.1.8 Status: Connected to B9K~OP3 Audio Output Audio Input Level Record to File Input Select: 44.1 kHz Minimize to Master Volume Mute >>>> Hidden Text <<<< Slider2 Mute OK Cancel Label Balance Slider1 Volume Front L/R Fr C/LFE Side L/R Back L/R
      I am attaching the program in question so you don't have to install it (i don't know if it is portable enough, tough): 

      SoundWire Server_files.zip

      Thanks in advance and I hope I didn't post in the wrong section
    • By WoodGrain
      Hi All,
      I've bought a Ergodox EZ programmable keyboard with layers of key maps (eg, layer 0 = dvorak, layer 1 = numberpad & nav, layer 2 = qwerty, etc), I've also got a small USB screen that can pull information from the registry. What I would like to determine is a way to pull the value of each current key from the keyboard, I can then write the values to the registry and pull them into my USB screen so I can see the keyboard key layout.
      I'm stuck with retrieving the key values, I've looked at _IsPressed(), _WinAPI_GetKeyState(), _WinAPI_GetKeyboardState(), _WinAPI_GetKeyboardType(), _WinAPI_GetKeyNameText(), but none of them appear to be able to pull the keyboard key values without user interaction.
      The idea being, in pseudo code, bear in mind no error checking etc in this code, "GetKeyValue()" is what I'm needing help with and is a made up function, as is "HardwareKey1" etc:
      $keyOnePrev = "" $numOfKeys = 76 While 1 $keyOneCurrent = GetKeyValue(HardwareKey1) If $keyOneCurrent <> $keyOnePrev Then For $key = 1 To $numOfKeys $keyToWrite = GetKeyValue(HardwareKey & $key) RegWrite("HKEY_CURRENT_USER\Software\myKeyboard", "key" & $key, "REG_SZ", $keyToWrite) Next EndIf $keyOnePrev = $keyOneCurrent Sleep(5000) WEnd Thanks guys!
    • By TheAutomator
      Is this better to check a variable before you assign it to a value that could be the same?
      for example:
      local $EmptyLog = false func WriteLog($text) _guictrledit_appendtext($log, ($EmptyLog ? @CRLF : $empty) & $text) If $EmptyLog Then $EmptyLog = False endfunc or does AutoIt behind the scenes already check this?
      i guess overwriting memory with the same value over and over again is not good if you can prevent this with a check?
    • By xEviiLx
      I'm trying to read value of a base pointer + offset.
      With only address I can easily the value but with base addres (pointer) I really don't know how I can do that.
       
    • By nacerbaaziz
      Hi all
      I want a way to get the last key pressed.
      I have a program that works with keyboard shortcuts and I want to  give the permission for the user to edit shortcut keys depending on what suits him
      i  want to make read-only edit box and the program writes the latest shortcut key pressed
      Please help me,
      greetings to all
      And thanks in advance
×
×
  • Create New...