My input function and len function does not return a correct result in some cases - input

I have a question I wrote this script to format an arabic text to a certain format. But I found a problem then when I type a longer sentence it adds more dots then there are letters. I will paste the code here and explain what the problem is.
import itertools
while True:
input_cloze_deletion = input("\nEnter: text pr 'exit'\n> ")
input_exit_check = input_cloze_deletion.strip().lower()
if input_exit_check == "exit":
break
# copy paste
interpunction_list = ["الله", ",", ".", ":", "?", "!", "'"]
# copy paste
interpunction_list = [ ",", ".", ":", "?", "!", "'", "-", "(", ")", "/", "الله", "اللّٰـه"]
text_replace_0 = input_cloze_deletion.replace(",", " ,")
text_replace_1 = text_replace_0.replace(".", " .")
text_replace_2 = text_replace_1.replace(":", " :")
text_replace_3 = text_replace_2.replace(";", " ;")
text_replace_4 = text_replace_3.replace("?", " ?")
text_replace_5 = text_replace_4.replace("!", " !")
text_replace_6 = text_replace_5.replace("'", " ' ")
text_replace_7 = text_replace_6.replace("-", " - ")
text_replace_8 = text_replace_7.replace("(", " ( ")
text_replace_9 = text_replace_8.replace(")", " ) ")
text_replace_10 = text_replace_9.replace("/", " / ")
text_replace_11 = text_replace_10.replace("الله", "اللّٰـه")
text_split_list = text_replace_11.split()
count_number = []
letter_count_list = []
index_list = itertools.cycle(range(1, 4))
for letter_count in text_split_list:
if letter_count in interpunction_list:
letter_count_list.append(letter_count)
elif "ـ" in letter_count:
letter_count = len(letter_count) - 1
count_number.append(letter_count)
print(letter_count)
else:
letter_count = len(letter_count)
count_number.append(letter_count)
print(letter_count)
for count in count_number:
letter_count_list.append(letter_count * ".")
zip_list = zip(text_split_list, letter_count_list)
zip_list_result = list(zip_list)
for word, count in zip_list_result:
if ((len(word)) == 2 or word == "a" or word == "و") and not word in interpunction_list :
print(f" {{{{c{(next(index_list))}::{word}::{count}}}}}", end="")
elif word and count in interpunction_list:
print(word, end = "")
else:
print(f" {{{{c{(next(index_list))}::{word}::{count}}}}}", end="")
when I type كتب عليـ ـنا و علـ ـي
the return is {{c1::كتب::...}} {{c2::عليـ::...}} {{c3::ـنا::...}} {{c1::و::..}} {{c2::علـ::..}} {{c3::ـي::..}}
but it should be
{{c1::كتب::...}} {{c2::عليـ::...}} {{c3::ـنا::..}} {{c1::و::.}} {{c2::علـ::..}} {{c3::ـي::.}}
I add a print function the print the len() results and the result is correct but it add an extra dot in some case.
But when I type just a single "و" it does a correct len() function but when I input a whole sentence it add an extra dot and I don't know why.
please help

Related

How to properly clean column header in Power Query and capitalize first letter only without changing other letter?

I would like to clean a column Header of the table so that my column header that has a name like below:
[Space][Space][Space]First Name[Space][Space]
[Space]MaintActType[Space]
TECO date[Space]
FIN Date
ABC indicator
COGS
Created On
And my desired Column Header Name to be like below:
First Name
Main Act Type
TECO Date
FIN Date
ABC Indicator
COGS
Created On
my code is as below:
let
Source = Excel.Workbook(File.Contents("C:\RawData\sample.xlsx"), null, true),
#"sample_Sheet" = Source{[Item="sample",Kind="Sheet"]}[Data],
#"Promoted Headers" = Table.PromoteHeaders(#"sample_Sheet", [PromoteAllScalars=true]),
#"Trim ColumnSpace" = Table.TransformColumnNames(#"Promoted Headers", Text.Trim),
#"Split CapitalLetter" = Table.TransformColumnNames(#"Trim ColumnSpace", each Text.Combine(Splitter.SplitTextByPositions(Text.PositionOfAny(_, {"A".."Z"},2)) (_), " ")),
#"Remove DoubleSpace" = Table.TransformColumnNames(#"Split CapitalLetter", each Replacer.ReplaceText(_, " ", " ")),
#"Capitalise FirstLetter" = Table.TransformColumnNames(#"Remove DoubleSpace", Text.Proper),
#"Remove Space" = Table.TransformColumnNames(#"Capitalise FirstLetter", each Text.Remove(_, {" "})),
#"Separate ColumnName" = Table.TransformColumnNames(#"Remove Space", each Text.Combine(Splitter.SplitTextByCharacterTransition({"a".."z"}, {"A".."Z"}) (_), " "))
in
#"Separate ColumnName"
However, i get the result as below. Which is not what i wanted as all the capital letter we combined together. How do i change the code so that i get the result as wanted? I would really appreciate your help, please.
First Name
Main Act Type
TECODate
FINDate
ABCIndicator
COGS
Created On
Alternatively, i changed the code to:
let
Source = Excel.Workbook(File.Contents("C:\RawData\sample.xlsx"), null, true),
#"sample_Sheet" = Source{[Item="sample",Kind="Sheet"]}[Data],
#"Promoted Headers" = Table.PromoteHeaders(#"sample_Sheet", [PromoteAllScalars=true]),
#"Trim ColumnSpace" = Table.TransformColumnNames(Input, Text.Trim),
#"Separate ColumnName" = Table.TransformColumnNames(#"Trim ColumnSpace", each Text.Combine(Splitter.SplitTextByCharacterTransition({"a".."z"}, {"A".."Z"}) (_), " ")),
#"Capitalise FirstLetter" = Table.TransformColumnNames(#"Separate ColumnName", Text.Proper)
in
#"Capitalise FirstLetter"
Unfortunately it return the result like so:
First Name
Main Act Type
Teco Date
Fin Date
Abc Indicator
COGS
Created On
I have no idea how to play around the code anymore.
One way is to mark the existing spaces with something (I used "ZZZ") and restore them back to spaces at the end. Here's your code with a couple of tweaks. Thanks for your code. I was trying to do Text.Proper and your sample helped me!
let
Source = Input,
#"Replaced Value" = Table.ReplaceValue(Source,"[Space]"," ",Replacer.ReplaceText,{"Headers"}),
#"Transposed Table" = Table.Transpose(#"Replaced Value"),
#"Promoted Headers" = Table.PromoteHeaders(#"Transposed Table", [PromoteAllScalars=true]),
#"Trim ColumnSpace" = Table.TransformColumnNames(#"Promoted Headers", Text.Trim),
#"Change space to ZZZ" = Table.TransformColumnNames(#"Trim ColumnSpace", each Replacer.ReplaceText(_, " ", " ZZZ ")),
#"Split CapitalLetter" = Table.TransformColumnNames(#"Change space to ZZZ", each Text.Combine(Splitter.SplitTextByPositions(Text.PositionOfAny(_, {"A".."Z"},2)) (_), " ")),
#"Capitalise FirstLetter" = Table.TransformColumnNames(#"Split CapitalLetter", Text.Proper),
#"Remove Space" = Table.TransformColumnNames(#"Capitalise FirstLetter", each Text.Remove(_, {" "})),
#"Separate ColumnName" = Table.TransformColumnNames(#"Remove Space", each Text.Combine(Splitter.SplitTextByCharacterTransition({"a".."z"}, {"A".."Z"}) (_), " ")),
#"Change ZZZ to space" = Table.TransformColumnNames(#"Separate ColumnName", each Replacer.ReplaceText(_, "ZZZ", " ")),
#"Remove DoubleSpace" = Table.TransformColumnNames(#"Change ZZZ to space", each Replacer.ReplaceText(_, " ", " "))
in
#"Remove DoubleSpace"

I am trying to check if a value isl Resistant in a table from a Form using dlookup

I am trying to lookup a value in a table for a particular patient ID and see whether that patient has the value Resistant. If so then disable a particular button on the form. I tried the following dlookup but it's giving me compiler error:
If DLookup("Rifampicin", "TableGeneXpert", "[PatientID] = " & Forms.FrmTreatment!PatientID) = Resistant Then
Me.btnDSTMatch.Enabled = True
Else
Me.btnDSTMatch.Enabled = False
Try with:
If DLookup("Rifampicin", "TableGeneXpert", "[PatientID] = " & Forms.FrmTreatment!PatientID & "") = "Resistant" Then
Me.btnDSTMatch.Enabled = True
Else
Me.btnDSTMatch.Enabled = False
End If
Or perhaps directly:
Me.btnDSTMatch.Enabled = IsNull(DLookup("Rifampicin", "TableGeneXpert", "[PatientID] = " & Forms.FrmTreatment!PatientID & " And [Rifampicin] = 'Resistant'"))
To filter on the latest date you can include a DMax expression or (the little known option) an SQL filter:
Me.btnDSTMatch.Enabled = IsNull(DLookup("Rifampicin", "TableGeneXpert", "[PatientID] = " & Forms.FrmTreatment!PatientID & " And [Rifampicin] = 'Resistant' And [JournalDate] = (Select Max([JournalDate]) From TableGeneXpert Where [PatientID] = " & Forms.FrmTreatment!PatientID & " And [Rifampicin] = 'Resistant')"))

Trouble with break statement in While loop

I'm trying to write a program that collects information from the user, then outputs to a text file. The program collects input correctly, as the print statement I inserted tells me, but the break statement doesn't break the loop when the specified value is input, and the output file is never updated. Any suggestions you could give would really help. Thanks!
# 1. Define Greeting:
def greeting():
print("Welcome, user! Please enter the address data, or type 'quit'.")
# 2. Input
def inputData():
name = input("Enter the name: ")
address = input("Enter the address: ")
city = input("Enter the city: ")
state = input("Enter the state: ")
zipCode = input("Enter the zip: ")
phone = input("Enter the phone number: ")
addressData = str(name + ", " + address + ", " +
city + ", " + state + ", "+ zipCode +
", " + phone)
print(addressData)
return(name)
# 3. Write data to text file
def dataWrite():
f.write(addressData + "\n")
# 4. Display the goodbye message:
def goodbye():
print("Have a nice day!")
# 5. Define Main function:
def main():
greeting()
while name != "quit":
inputData()
if name == "quit":
break
else:
dataWrite()
f.close()
goodbye()
main()
def main():
greeting()
while name != "quit":
name = inputData()
if name == "quit":
break
else:
dataWrite()
f.close()
goodbye()
You are not getting the return value of inputData().

groovy closure instantiate variables

is it possible to create a set of variables from a list of values using a closure??
the reason for asking this is to create some recursive functionality based on a list of (say) two three four or five parts
The code here of course doesn't work but any pointers would be helpful.then
def longthing = 'A for B with C in D on E'
//eg shopping for 30 mins with Fiona in Birmingham on Friday at 15:00
def breaks = [" on ", " in ", "with ", " for "]
def vary = ['when', 'place', 'with', 'event']
i = 0
line = place = with = event = ""
breaks.each{
shortline = longthing.split(breaks[i])
longthing= shortline[0]
//this is the line which obviously will not work
${vary[i]} = shortline[1]
rez[i] = shortline[1]
i++
}
return place + "; " + with + "; " + event
// looking for answer of D; C; B
EDIT>>
Yes I am trying to find a groovier way to clean up this, which i have to do after the each loop
len = rez[3].trim()
if(len.contains("all")){
len = "all"
} else if (len.contains(" ")){
len = len.substring(0, len.indexOf(" ")+2 )
}
len = len.replaceAll(" ", "")
with = rez[2].trim()
place = rez[1].trim()
when = rez[0].trim()
event = shortline[0]
and if I decide to add another item to the list (which I just did) I have to remember which [i] it is to extract it successfully
This is the worker part for then parsing dates/times to then use jChronic to convert natural text into Gregorian Calendar info so I can then set an event in a Google Calendar
How about:
def longthing = 'A for B with C in D on E'
def breaks = [" on ", " in ", "with ", " for "]
def vary = ['when', 'place', 'with', 'event']
rez = []
line = place = with = event = ""
breaks.eachWithIndex{ b, i ->
shortline = longthing.split(b)
longthing = shortline[0]
this[vary[i]] = shortline[1]
rez[i] = shortline[1]
}
return place + "; " + with + "; " + event
when you use a closure with a List and "each", groovy loops over the element in the List, putting the value in the list in the "it" variable. However, since you also want to keep track of the index, there is a groovy eachWithIndex that also passes in the index
http://groovy.codehaus.org/GDK+Extensions+to+Object
so something like
breaks.eachWithIndex {item, index ->
... code here ...
}

Change syntax using regular expression

I have some inherited legacy language code snippets stored in a database table that I need to transform to a SQL like syntax so it can be used more effectively.
For example, one of the snippets is of the form
keyword = [a,b,c,x:y,d,e,f,p:q]
to indicate either discrete comma separate values or a range of colon-delimited values
How can I transform this to the equivalent SQL friendly snippet which would be
keyword in (a,b,c) or keyword between x and y or keyword in (d,e,f) or keyword between p and q
Thanks
It isn't regex but the first this that comes to mind it extracting the text within the square brackets so you have
textVariable = a,b,c,x:y,d,e,f,p:q
then split with the columns so you have an array where each element is part of the string. So your resulting array would be
array[0] = a
...
array[3] = x:y
...
Then go through your array and create the final string you want. something like this (though it isn't tested)
finalString = ""
tempString = ""
for (int i = 0, i < array.length; i++) {
if (array[i].contains(":")) { // then it needs to be between the two values
if (finalString.length > 0) {
finalString = finalString + " or "; // need to add an 'or'
}
if (tempString.length > 0) { // then need to add the keyword in (...) to finalString
finalString = finalString + tempString + ") or ";
}
temparray = array[i].split(":")
finalString = finalString + " keyword between " + temparray[0] + " and " + temparray[1]
} else {
if (tempString.length = 0) {
tempString= "keyword in ("; // need to start the next set
} else {
tempString = tempString + ", "
}
tempString = tempString + array[i];
}
}