write a function in JES that will distinguish type of file is chosen - jes

"Write a function that will obtain a file name (using pickAFile), and then recognise if it is a picture or a sound file, or even some other file type. The file should then be interpreted as either a picture, if its type is jpg (then print an appropriate message, then exit) or a sound, if its type is wav (then print an appropriate message, then exit), and if it is neither a picture nor a sound file, then an error message must be printed. This error message should include the type of the file (or the lack of a type, e.g. a file name that might not have a period in it, e.g. ducksjpg). Remember that file types can be 2, 3, 4 or even more letters long! "
So this is what I have figured out so far and it works:
def sortoutfiles():
f= pickAFile()
print f
filename=f
if filename.endswith (".jpg"):
print "It's a picture"
if filename.endswith (".wav"):
print " It's a sound"
else:
print"Oops! Did not choose a picture or a sound file"
For some reason the program doesnt work when I try to use rfind-get error message-invalid syntax on line 5
def sortoutfiles():
f= pickAFile()
print f
filename=f
if p=filename.rfind('.jpg'):
print "It's a picture"
if filename=f.rfind(".wav"):
print " It's a sound"
else:
print"Oops! Did not choose a picture or a sound file"
here
Can someone tell me what I am doing wrong in writing the program using rfind?

Apco 1P00?
Use rfind to figure out the file extension
f = pickAFile()
p = f.rfind('.jpg') #finds if the file ends in .jpg
s = f.rfind('.wav') #finds if the file ends in .wav
length = len(f) #finds the length of the file name
Use this as a foundation and go from here using if statements.
Recall the last lab.
>>> testString = 'abc DEf ghi ihg uVW xyz'
>>> print testString.find('k')
-1 #"Not found" can't be 0, so result is -1

Related

Replacement of text in xml file by AHK - get error when trying to open as xml file

I am using an AHK script to replace some text in an .xml file (Result.xml in this case). The script then saves a file as Result_copy.xml. It changes exactly what I need, but when I try to open the new xml file, it won't open, giving me the error:
This page contains the following errors:
error on line 4 at column 16: Encoding error
Below is a rendering of the page up to the first error.
I only replaced text at line 38 using:
#Include TF.ahk
path = %1%
text = %2%
TF_ReplaceLine(path, 38, 38, text)
%1% and %2% are given by another program and are working as should
I also see that the orginal Result.xml is 123 kb and Result_copy.xml is 62 kb, even though I only add text. When I take Result.xml and manually add the text and save it, it's 123 kb and still opens. so now both files contain exactly the same Characters, but one won't open as xml. I think that something happens during saving/copying, which I don't understand.
Could someone help me out on this one? I don't have a lot of experience in AHK scripting and do not have a programming background.
Thank you in advance!
Michel
TF.ahk contains this:
/*
Name : TF: Textfile & String Library for AutoHotkey
Version : 3.8
Documentation : https://github.com/hi5/TF
AutoHotkey.com: https://www.autohotkey.com/boards/viewtopic.php?f=6&t=576
AutoHotkey.com: http://www.autohotkey.com/forum/topic46195.html (Also for examples)
License : see license.txt (GPL 2.0)
Credits & History: See documentation at GH above.
TF_ReplaceLine(Text, StartLine = 1, Endline = 0, ReplaceText = "")
{
TF_GetData(OW, Text, FileName)
TF_MatchList:=_MakeMatchList(Text, StartLine, EndLine, 0, A_ThisFunc) ; create MatchList
Loop, Parse, Text, `n, `r
{
If A_Index in %TF_MatchList%
Output .= ReplaceText "`n"
Else
Output .= A_LoopField "`n"
}
Return TF_ReturnOutPut(OW, OutPut, FileName)
}

Having trouble conditionally moving files based on their names

I am trying to write a script that will auto sort files based on the 7th and 8th digit in their name. I get the following error: "Argument must be a string scalar or character vector". Error is coming from line 16:
Argument must be a string scalar or character vector.
Error in sort_files (line 16)
movefile (filelist(i), DirOut)
Here's the code:
DirIn = 'C:\Folder\Experiment' %set incoming directory
DirOut = 'C:\Folder\Experiment\1'
eval(['filelist=dir(''' DirIn '/*.wav'')']) %get file list
for i = 1:length(filelist);
Filename = filelist(i).name
name = strsplit(Filename, '_');
newStr = extractBetween(name,7,8);
if strcmp(newStr,'01')
movefile (filelist(i), DirOut)
end
end
Also, I am trying to make the file folder conditional so that if the 10-11 digits are 02 the file goes to DirOut/02 etc.
First, try avoid using the eval function, it is pretty much dreaded as slow and hard to understand. Specially if you need to create variables. Instead do this:
filelist = dir(fullfile(DirIn,'*.wav'));
Second, the passage:
name = strsplit(Filename, '_');
Makes name a list, so you can access name{1} or possibly name{2}. Each of these are strings. But name isn't a string, it is a list. extractBetween requires a string as an input. That is why you are getting this problem. But note that you could have simply done:
newStr = name(7:8);
If name was a string, which in Matlab is a char array.
EDIT:
Since it has been now claimed that the error occurs on movefile (filelist(i), DirOut), the likely cause is because filelist(i) is a struct. Wheres a filena name (char array) should have been given at input. The solution should be replacing this line with:
movefile(fullfile(filelist(i).folder, filelist(i).name), DirOut)
Now, if you want to number the output folders too, you can do this:
movefile(fullfile(filelist(i).folder, filelist(i).name), [DirOut,filesep,name(7:8)])
This will move a file to /DirOut/01. If you wanted /DirOut/1, you could do this:
movefile(fullfile(filelist(i).folder, filelist(i).name), [DirOut,filesep,int2str(str2num(name(7:8)))])

Am trying to read a population_data.json file but when ever i run the code it doesn't display any data in the file and i don't get any Error too?

import json
#Load the data into a list.
filename = 'population_data.json'
with open(filename)as f:`enter code here`
pop_data = json.load(f)
enter code here
#Print the 2010 population data for each country.
for pop_dict in pop_data:`enter code here`
if pop_dict['Year'] == '2010':
country_name = pop_dict['Country Name']
population = int(float(pop_dict['Value']))
print(country_name + " : " + str(population))
Am trying to extract data from a population_data.json file, but whenever i run my code it doesn't show any result and i don't get any Errors, i have save the population data file in the same folder with the code but i still have that same problem, i don't get any result of the data in the shell. i would be glad if someone can help.Thank you .
enter code here
import json
#Load the data into a list.
filename = 'population_data.json'
with open(filename)as f:`enter code here`
pop_data = json.load(f)
enter code here
#Print the 2010 population data for each country.
for pop_dict in pop_data:`enter code here`
if pop_dict['Year'] == '2010':
country_name = pop_dict['Country Name']
population = int(float(pop_dict['Value']))
print(country_name + " : " + str(population))
I would suggest starting your script in the python debugger (pdb). You can start it either by starting your script like this:
python3 -m pdb your_script.py
or by importing the pdb module. Adding the following line into your python file (for example after import json, or any other):
import pdb; pdb.set_trace()
Once it is loaded, the debugger stops at the first instruction and shows the debugger promt (Pdb) . Continue execution line by line by typing next and hitting ENTER until you hit a line where something interesting is happening. The debugger prints always the next instruction and the script path and line.
Debugger output is added below, everything after (Pdb) you have to type and confirm with ENTER
(Pdb) next
> /path/to/your_script.py(7)<module>()
-> pop_data = json.load(f)
(Pdb) next
> /path/to/your_script.py(11)<module>()
-> for pop_dict in pop_data:
Now let the debugger print contents of a variable
(Pdb) p pop_data
{"Probably": "something", "you": "don't expect here"}
I suspect either the for loop yields 0 pop_dicts and therefore the loop body is never executed, or no pop_dict key Year has value 2010 and the if body is never executed.
Alternative to type next often (== single stepping): set a break point on a specific line (your_script.py:11), and continue execution until the breakpoint is hit
(Pdb) break your_script.py:11
Breakpoint 1 at /path/to/your_script.py:11
(Pdb) continue
> /path/to/your_script.py(11)<module>()
-> for pop_dict in pop_data:
(Pdb)
For additional debugger commands see pdb commands

ahk: how to read non txt file and save infos to variables?

i have a replay file from a game (world of tanks) and i want to read infos from it and store them to variables.
when i open the file with notepad there seems to be some xml "code" witch contains some of the infos i want and then there starts the replay file data so its only gibberish. example: http://pastebin.com/faBPUn1d
i tried to extract the first line with FileReadLine but the variable contains only crap :(
how can i read the file with ahk, store infos like "damageDealt": 9321 to a variable?
thank you for your help
This is a JSON data inside a binary file so use FileOpen function to open it.
There are two JSON blocks and each one is prefixed by its length (NumGet or File.ReadUInt or similar to the rescue) so you can use it extract the block and pass it to AutoHotkey-JSON parser.
And then you will be able to access the object hierarchically or enumerate it like any object:
result.personal["14337"].details["(9291360, 7169)"].damageDealt.
Example:
#include JSON.ahk ; download from https://github.com/cocobelgica/AutoHotkey-JSON
; read the data
f := fileOpen("14473423299267_usa_A02_M2_lt_thepit.wotreplay", "r")
f.seek(8)
data1 := JSON.load(f.read(f.readUInt()))
data2 := JSON.load(f.read(f.readUInt()))
f.close()
; write the data as pretty-formatted JSON
f := fileOpen("data1.json", "w"), f.write(JSON.dump(data1,,"`t")), f.close()
f := fileOpen("data2.json", "w"), f.write(JSON.dump(data2,,"`t")), f.close()
; load the first item of 'data2[1].personal' object into personalInfo
data2[1].personal._NewEnum().Next(k, personalInfo)
msgbox % "playerName: " data1.playerName "`n"
. "dateTime: " data1.dateTime "`n"
. "mapName: " data1.mapName "`n"
. "`n"
. "damageDealt: " personalInfo.damageDealt "`n"

how to search for a sub string within a string in QBasic

I am creating a simple chat programme in QBasic that will answer questions based on some specific key words present in the user input.therefore I need a way to search for a sub string (I.e. A specific word)within a string.
So, please help me.
To find out if a string contains a certain (sub-)string, you can do this:
text$ = "nonsense !"
IF INSTR( text$, "sense" ) >= 1 THEN
PRINT "This text makes sense !"
END IF
And no, I was not able to test this, as a no longer have QBasic on my PC ;-)
According to the link from the comment above >= 1 is ok
I think INSTR is usually used as follows:
sent$ = "This is a sentence"
PRINT INSTR(1, sent$, "is")
PRINT INSTR(4, sent$, "is")
PRINT INSTR(1, sent$, "word")
the first PRINT command will print a '3' since the first location of "is" within the sentence is at position 3. (The 'is' in 'This')
the second PRINT command starts searching at position 4 (the 's' in 'This'), and so finds the "is" at position 6. So it will print '6'.
the third PRINT command will print a '0' since there is no instance of "word" in the sentence.
Counts the occurrences of a substring within a string.
T$ = "text to be searched and to be displayed"
S$ = "to"
l = 1
DO
x = INSTR(l, T$, S$)
IF x THEN
n = n + 1
l = x + LEN(S$)
ELSE
EXIT DO
END IF
LOOP
PRINT "text '"; S$; "' matches"; n; "times."