How to get the count of a class with AppleScript? - css

Learning AppleScript I'm trying to practice and I wanted to see if I could get the count of a class in an .xhtml file.
In my BBEdit project I set a variable for the project with:
set this_project to file of project document 1
made sure to target all the .xhtml files with:
set total_xhtml to {search mode:grep, case sensitive:false, match words:false, extend selection:false, returning results:true, filter:{ID:"111232452", filter_mode:and_mode, filter_terms:{{operand:"xhtml", field:«constant ****FnSf», operator:op_is_equal}}}}
but when I try to count the class for each file I'm stumped..
I did try:
set varCount to count class=\"foobar\"" of (this_project in total_xhtml)
If I try set varCount to count class=\"foobar\"" it returns a number in the AppleScript Editor but how can I get the full count for each file in a project?

If I understand what you're asking, you want to find out how many times your class is listed in your different .xhtml files.
If that's what you're trying to accomplish, the below is a working example that should do what you're looking for.
on run
try
set foundItems to do shell script "grep -ri 'yourClassName' " & quoted form of "/Path/to/Your/directory"
on error
set foundItems to ""
end try
set oldDelims to AppleScript's text item delimiters -- save their current state
set AppleScript's text item delimiters to {return} -- declare new delimiters
set tempList to every text item of foundItems
set AppleScript's text item delimiters to oldDelims -- restore them
set foundCount to count of tempList
end run

Just realized I never accepted an answer to my question and I wanted to close out this Q&A. I didn't choose the provided answer because text item delimiters were firing an incorrect count from the file and I wanted an approach that didn't call on a do shell.
In AppleScript and BBEdit if you reference the Dictionary there is FIND:
and with a repeat loop I was able to step through each occurrence of class="foobar":
## beginning of file
select insertion point before first character of text document text document 1
set countClass to 0
repeat
## find pattern
set findClass to find "class=\"foobar\"" searching in text 1 of text document text document 1 options {options} with selecting match
## exit after no more patterns
if not found of findClass then exit repeat
## increment for every occurrence
set countClass to countClass + 1
end repeat
## return total count of pattern
return countClass
With the above repeat I was able to step through each file and total up every occurrence of class foobar. Hope this helps the next person.

Related

How to select a random word from a txt file in python version 3.4?

**
I have a txt file called 'All_Words' and it consist of 2000 words and i'm making a hangman so i needed to choose a random word i've already thought of picking a random number from 0 to 2000 and read the line of the number to chose but i don't know how to do that, also some background info:
i am in 8th grade and i like coding im trying to get better so i'm trying to get what people suggest and try to figure out what every part does and the reserved words such as 'global' for example
also i have also tried to just shuffle the txt file because i already got it to print the first word so if im a able to shuffle the txt file then it would print a different word an i could create an if statement saying if the word chosen was already chooses then it would shuffle it again and pick he first word again, also i got this idea of the shuffle the txt file from my dad but he only did something called 'dos' or something like that he said he did it before it was even called coding so i don't even know if it world word in python, and i've asked my coding teacher and he said he dont know how you would do that because he is use to java and javascript
this is what i have so far and also i would like it to only pick one word instead of every word in order:**
import random
with open("All_Words.txt") as file:
for line in file:
print(line)
break
Assuming each word is on a new line in file, you can read the text file into a list and use random.choice() to pick a random element in the list. Then you remove the word from the list so you don't pick it again.
import random
file = open("All_Words.txt", "r")
words = file.read()
listOfWords = words.split("\n")
randWord = random.choice(listOfWords)
print(randWord)
listOfWords.remove(randWord)
newUnqiueRandWord = random.choice(listOfWords)
print(newUnqiueRandWord)

How to check if data shows in html table else if the data didn't show in the table it will failed using robot framework

I have a new problem in my automation testing and I need to check if the data in my tables exist.
For Example.. I have a table below. I need to check if the cat and dog exist in the table.. else it will failed. so I create a run keyword if to verify if the data exist but first I need to get all the data because sometimes he table is dynamic. This is my sample code. my problem is.. what if the data(Dog) didn't exist in the table?
${Count} get element count ${Table_Row}
FOR ${i} IN RANGE 1 ${Count}
${Animals} get text xpath=//div[#id='table1']/table/tbody/tr/td[41]/div/table/tbody/tr[${i}]/td
Run Keyword If "${Animals}" == "Dog" Log to console Dog Exist ELSE fail Dog didn't exist
END
What you need is to get all the elements of first column into a array, something like:
${animals} Get WebElements xpath=//"xpath for all elements in first column"
then with that you can run a for cycle to check each element and fail the test if you don't find whatever you need to find:
FOR ${element} in #{animals}
${animal} Get Text ${element}
Log To Console ${animal}
END
You can check first expected data exists or not
${data}= Page Should Contain Element element xpath
if not exists you can fail the test.
Please let me know if I am not understood your question correctly..

How to verify text but except some text in line using robot framework

I have to verify text that present on web page but in the text line have dynamic wording that I don't know how to verify this situation.
Wait Until Element Contains &{verScript}[Script] Test automate for 50,000 time timeout=60s
I want to verify text "Test automate for 50,000 time" but 50,000 is dynamic value. I don't want to verify 50,000 in this locator and can it whatever for this value in line.
Can any help me please.
using set
#{queryResultsA}= split string Test automate for 50,000 time
#{queryResultsB}= split string Test automate for XX,XXX time
${z} = Evaluate (set(${queryResultsA}) - set(${queryResultsB}))
## here ${z} will be 50,000
Using keyword
will return all lines on the page which are matching given string. the following keyword will return Lines as one string concatenated back together with newlines
Get Lines Containing String Test automate for
for more keywords
which match partial and full text/strings
using regex and pattern matching

How do I make my Python3 string matching code ignore files that do not match any criteria?

I have a Python3 script that reads the first eight characters of every filename in a directory in order to determine whether the file was created before or after 180 days ago based on each file's name. The file names all begin with YYYYMMDD or eerasedd_YYYYMMDD_etc.xls. I can collect all these filenames already.
I need to tell my script to ignore any filename that does not conform to the standard eight leading numerical characters, example: 20180922 or eerasedd_20171207_1oIkZf.so.
if name.startswith('eerasedd_'):
fileDate = datetime.strptime(name[9:17], DATEFMT).date()
else:
fileDate = datetime.strptime(name[0:8], DATEFMT).date()
I need logic to prevent the script from choking on files that don't fit the desired pattern. The script needs to carry on with its work and forget about non-conformant filenames. Do I need to add code that causes an exception or just add an elif block?
I have a function to get only the names of those files I need based on their extensions.
def get_files(extensions):
all_files = []
for ext in extensions:
all_files.extend(Path('/Users/mrh/Python/calls').glob(ext))
for file in get_files(('*.wav', '*.xml')):
print (file.name)
Now I need to figure out how to check each 'file.name' for the date string in its filename. i.e. now I need to run something like
if name.startswith('eerasedd_'):
fileDate = datetime.strptime(name[9:17], DATEFMT).date()
else:
fileDate = datetime.strptime(name[0:8], DATEFMT).date()
against 'file.name' to see whether the files are 180 days old or less.

inserting line breaks after every record in the textpad

I have a textpad file that has rows of text. For e.g.
Cat: Meaning - animal. The cat ran up the house
Rat: Meaning- rodent. The rat lives in the borough and feeds on leftovers
Word 3: Description
Word 4: Description
I have many such record in my file. I want to insert a line break at the end of every record for proper presentation. Doing it manually is tedious. Please help if you know an automated process to insert line break.
You can quickly do this by using a feature called "Regular Expressions" to find and add empty lines.
Open up the Find/Replace (Search menu > Replace)
In the "Find what" field, type the following: (^.+$)\n(^.+$)
In the "Replace with" field, type the following: \1\n\n\2
Tick the "Regular expression" checkbox
Click the Replace All button at least twice, but perhaps 3 times, until you get the message Cannot find the Regular Expression
Untick the "Regular expression" checkbox
Close the Replace dialog
Confirm the file is formatted as you are expecting
Save the file.
You can write a simple C# prgram that uses a loop that adds this code after every line :
But first add the namespace using System.Enviorment
Enviorment.NewLine;
If you have any more trouble i'll help with some code to get started
Open up the Find/Replace (Search menu > Replace)
In the "Find what" field, type the following so that the replace occurs at the end of each line: $
In the "Replace with" field, type the following. Note each 'n' represents a <return>. In this instance, I added a return at the end of a SQL statement, the word 'GO' on the next line and another <return>: \n\GO\n
Started with text file containing:
select * from <tablename>
select * from <tablename>
Ended with text file containing:
select * from <tablename
GO
select * from <tablename>
GO
Hope that helps.
from your text it is difficult to understand what you are intending to do. I'll give you some questions. The answers will help others to help you.
Do you really mean textpad as the product from company helios in UK or do you use this word as a general word for a class of tools (like notepad - but there is a general definition AND the tool as part of Windows).
Your file hase line breaks yet. You don't see them, but in the file itself they are present (in Unix systems line feed (hex code 0A) or in the windows world carriage return followed by line feed (hex code 0D 0A)).
Or would you like to publish your text in HTML? So you have to put the necessary tags around each line like paragraph, line break, list item etc.?

Resources