I wrote a program that selects random words from lists to make a sentence. I want to write grammar rules for this. Right now I am working on plurals.
I want to add an s or es to the end of the selected word in 'nouns' if the word "those" is selected from list5.
import random
class Wrds(object):
verbs = [
"walk", "run"
]
pronouns = [
"I", "you"
]
help_verbs = [
"will", "might"
]
nouns = [
"boy", "girl"
]
list5 = [
"the", "that", "this", "a", "those"
]
punctuation = [
".", "?", "!"
]
def result(self):
a = random.choice(Wrds.verbs)
b = random.choice(Wrds.pronouns)
c = random.choice(Wrds.help_verbs)
d = random.choice(Wrds.nouns)
e = random.choice(Wrds.list5)
f = random.choice(Wrds.punctuation)
print "%s %s %s %s %s%s" % (b, c, a, e, d, f)
def ask():
a = raw_input("> ")
if a == "go":
w = Wrds()
return w.result()
elif a == "exit":
exit()
while True:
ask()
Before the print statement in the result method, add:
if e == 'those':
d += 's'
Related
For instance the function:
val reg = "[^ ]".r
takes in an input that would match with every character except for the empty space character.
and:
def matchReg(line: String): List[String] = reg.findAllIn(line).toList
Converts the input into a list.
However how would I edit this so that it would match with a non-single character input. Since it seems as though this splits the input such as "14" into "1" and "4" when the values of the regular expression are turned into a list. If the input is "14" I want it to output "14" rather than it being split. Thank you.
EDIT: I have written test cases to explain the type of output I am looking for
"The match" should "take list" in {
assert(matchReg("(d e f)") == List("(", "d", "e", "f", ")"))
}
it should "take numbers" in {
assert(matchReg("(12 45 -9 347 4)") == List("(", "12", "45", "-9", "347", "4", ")"))
}
it should "take operators" in {
assert(matchReg("(- 7 (* 8 9))") == List("(", "-", "7", "(", "*", "8", "9", ")", ")"))
}
With the following case, "take list" and "take operators" passes successfully if I use:
val reg = "[^ ]".r
However "take numbers" does not pass since numbers such as "347" are being split into "3" "4" and "7", when I want them to register as one single number.
This should work for you
val reg = """[^ \(\)]+|\(|\)""".r
You should add some other alternatives if you want to support also [ ] , { } or other operators
# matchReg("(d e f)")
res8: List[String] = List("(", "d", "e", "f", ")")
# matchReg("(12 45 -9 347 4)")
res9: List[String] = List("(", "12", "45", "-9", "347", "4", ")")
# matchReg("(- 7 (* 8 9))")
res10: List[String] = List("(", "-", "7", "(", "*", "8", "9", ")", ")")
jsondata = f.read()
dataList = json.loads(jsondata)
projectName = dataList['query']['project']
reportStartTime = dataList['query']['startTime']
reportEndTime = dataList['query']['endTime']
allEventList = dataList['sessionEvents']
'''We need a Type for each data so it will be
like startTime:endTime'''
flag = False
count = 0
esbulkData = []
for event in allEventList:
ls = event["l"]
del event["l"]
for l in ls:
llist = []
eventList = []
llist.append(l)
event["l"] = llist
eventList.append(event)
flurryData = { "project": projectName, "startTime": reportStartTime, "endTime": reportEndTime, "sessionEvents": eventList }
#{
# "_index": "tickets-index",
# "_type": "tickets",
# "_id": j,
# "_source": {
# "any":"data" + str(j),
# "timestamp": datetime.now()}
# }
esData = {"_index": "fl_ios_prod_feb_bulk", "_type": "flurryRawSchema", "_id": count, "_source": flurryData}
esbulkData.append(esData)
es = Elasticsearch([ES_URL])
res = helpers.bulk(es, esbulkData)
if (res):
print("Passed")
else:
print("Failed")
In above code, everything works just fine but doc_count don't go more than 500 while checking on "Sense". It seems to have deleted some docs.
Please help. I am having those nights
Okay So I forget to increase the count and that what was issue.
I want a pattern to match a string that has everything in it(alphabets,numbers,special charactres)
public static void main(String[] args) {
String retVal=null;
try
{
String s1 = "[0-9a-zA-Z].*:[0-9a-zA-Z].*:(.*):[0-9a-zA-Z].*";
String s2 = "BNTPSDAE31G:BNTPSDAE:Healthcheck:Major";
Pattern pattern = null;
//if ( ! StringUtils.isEmpty(s1) )
if ( ( s1 != null ) && ( ! s1.matches("\\s*") ) )
{
pattern = Pattern.compile(s1);
}
//if ( ! StringUtils.isEmpty(s2) )
if ( s2 != null )
{
Matcher matcher = pattern.matcher( s2 );
if ( matcher.matches() )
{
retVal = matcher.group(1);
// A special case/kludge for Asentria. Temp alarms contain "Normal/High" etc.
// Switch Normal to return CLEAR. The default for this usage will be RAISE.
// Need to handle switches in XML. This won't work if anyone puts "normal" in their event alias.
if ("Restore".equalsIgnoreCase ( retVal ) )
{
}
}
}
}
catch( Exception e )
{
System.out.println("Error evaluating args : " );
}
System.out.println("retVal------"+retVal);
}
and output is:
Healthcheck
Hera using this [0-9a-zA-Z].* am matching only alpahbets and numbers,but i want to match the string if it has special characters also
Any help is highly appreciated
Try this:
If you want to match individual elements try this:
2.1.2 :001 > s = "asad3435##:$%adasd1213"
2.1.2 :008 > s.scan(/./)
=> ["a", "s", "a", "d", "3", "4", "3", "5", "#", "#", ":", "$", "%", "a", "d", "a", "s", "d", "1", "2", "1", "3"]
or you want match all at once try this:
2.1.2 :009 > s.scan(/[^.]+/)
=> ["asad3435##:$%adasd1213"]
Try the following regex, it works for me :)
[^:]+
You might need to put a global modifier on it to get it to match all strings.
I have this regular expression which is what is allowed in the String.
^\pL*['#-]?\pL*\$
The requirements have changed and now I need to drop everything else from the String. For example only one of these special characters ', #, and - is allowed.
How can I change this regex to drop everything else that does not fit this ?
Here is the list of expected values:
JohnO'Connell -> allowed. should be as is.
JohnDias -> allowed. should be as is.
JohnOConnell' -> allowed. should be as is.
JohnOConnell# -> allowed. should be as is.
JohnOConnell- -> allowed. should be as is.
JohnOConnell-# -> should return JohnOConnell-
JohnOConn34ell -> should return JohnOConnell
*JohnOConnell -> should return JohnOConnell
JohnOConnell* -> should return JohnOConnell
JohnOConn$%ell -> should return JohnOConnell
Thanks
If I understand it correctly, you could do it this way:
// Test data
def tests = [ [ input:"JohnO'Connell", output:"JohnO'Connell" ],
[ input:"JohnDias", output:"JohnDias" ],
[ input:"JohnOConnell'", output:"JohnOConnell'" ],
[ input:"JohnOConnell#", output:"JohnOConnell#" ],
[ input:"JohnOConnell-", output:"JohnOConnell-" ],
[ input:"JohnOConnell-#", output:"JohnOConnell-" ],
[ input:"JohnOConn34ell", output:"JohnOConnell" ],
[ input:"*JohnOConnell", output:"JohnOConnell" ],
[ input:"JohnOConnell*", output:"JohnOConnell" ],
[ input:"JohnOConn\$%ell", output:"JohnOConnell" ] ]
String normalize( String input ) {
int idx = 0
input.replaceAll( /[^A-Za-z'#\-]/, '' ) // remove all disallowed chars
.replaceAll( /['#\-]/ ) { match -> // replace 2nd+ instance of special chars
idx++ == 0 ? match : ''
}
}
tests.each {
assert normalize( it.input ) == it.output
}
i am writing my helper methods for selenium tests. One of them is :
private static List<DataRow> parseTable(WebElement table) {
List<WebElement> tableHeaders = table.findElements(By.tagName("th"))
List<DataRow> dataRow = table.findElements(By.xpath(".//tbody/tr")).collect {
Map<String, String> columns = [:]
it.findElements(By.tagName("td")).eachWithIndex { item, i ->
columns[tableHeaders.get(i).text] = item.text
}
new DataRow(it, columns)
}
return dataRow
}
And i dont like this part:
it.findElements(By.tagName("td")).eachWithIndex { item, i ->
columns[tableHeaders.get(i).text] = item.text
}
Is there a better way to make map from two lists?
You should be able to do:
def columns = [tableHeaders,it.findElements(By.tagName("td"))].transpose().collectEntries()
By way of an explanation:
Given:
def a = [ 'a', 'b', 'c' ]
def b = [ 1, 2, 3 ]
Then
def c = [ a, b ].transpose()
assert c == [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
And:
def d = c.collectEntries()
assert d instanceof Map
assert d == [ a:1, b:2, c:3 ]