Doing english to pig-latin with python2, converting words with alphabets to pig-latin done, how to modify it to add numbers and special characters - python-2.x

Converting English and Special Characters to Pig Latin Script (as in https://lingojam.com/PigLatinTranslator ) using Python 2.
Done English to Pig Latin. Rest Pending.
Here the code
import re
def split_word(sentence):
temp=sentence
while temp[0] not in ['a','e','i','o','u','A','E','I','O','U']:
temp = temp[1:]
else:
t=temp
s=re.split(r'[a e i o u A E I O U]', sentence)
while len(s) > 1 :
s.pop()
j_sentence= ''.join(s)
print "\nCoressponding Pig-Latin translation :",t+j_sentence+"ay"+" "
return t+j_sentence+"ay"+" "
try:
while (True):
s=""
sentence=raw_input("\nEnter text to split or ctrl + D to exit : ").split(" ")
if sentence==['']:
print "\nPlease enter a sentence !!"
else:
for i in sentence:
s+=split_word(i)
except EOFError:
print "\n\nExited Sucessfully!!!"
pass
print s

Related

The wav file wont play after using pyinstaller --onefile.I just hear the windows 'beep'

This program displays a home circuit breaker panel. the user can view what is on each breaker on the panel (data taken from an imported dictionary of entered breaker panel info) or the user can check what breakers control any list zone (kitchen basement, etc) The breakerville program closes when the user decides and is supposed to play a wave file at the close. It doesn't play after the program is made into an exe with pyinstaller just the windows 'beep'.
I am suspecting that I may need to edit the spec file to get the wave file to work after compiled. Is this correct and if so how? Do I need to modify the spec file?
from playsound import playsound # CURRENTLY USING
from chart import chart
from BreakerZones import BreakerZones
import time
import sys
import colorama
import yaml # to print the nested_lookup results(n) on separate lines
from nested_lookup import nested_lookup, get_all_keys # importing 2 items from nested_lookup
from colorama import Fore, Back, Style
colorama.init(autoreset=True) # If you don't want to print Style.RESET_ALL all the time,
# reset automatically after each print statement with True
print(colorama.ansi.clear_screen())
print('\n'*4) # prints a newline 4 times
print(Fore.MAGENTA + ' Arriving-' + Fore.GREEN + ' *** BREAKERVILLE USA ***')
def main():
print('\n' * 2)
print(Fore.BLUE + ' Breaker Numbers and Zones')
k = get_all_keys(BreakerZones)
# raw amount of keys even repeats , has quotes
new_l = [] # eliminate extra repeating nested keys
for e in k: # has quotes
if e not in new_l and sorted(e) not in new_l: #
new_l.append(e) #
print()
new_l.sort() # make alphabetical
newer_l = ('%s' % ', '.join(map(str, new_l)).strip("' ,")) # remove ['%s'] brackets so they don't show up when run
print(' ', yaml.dump(newer_l, default_flow_style=False)) # strip("' ,") or will see leading "' ," in output
print(Fore.BLUE + ' ENTER A BREAKER # OR ZONE', Fore.GREEN + ': ', end='')
i = input().strip().lower() # these lines is workaround for the colorama
print() # user input() issue of 'code' appearing in screen output
if i in k:
n = (nested_lookup(i, BreakerZones, wild=False, with_keys=False)) # wild=True means key not case sensitive,
print(yaml.dump(n, default_flow_style=False)) # 'with_keys' returns values + keys also
# for key, value in n.items(): eliminated by using yaml
# print(key, '--', value) eliminated by using yaml
else:
print(Fore.YELLOW + ' Typo,' + Fore.GREEN + ' try again')
main()
print()
print(Fore.GREEN + ' Continue? Y or N: C for breaker chart : ', end='') # see comments ENTER A BREAKER
ans = input().strip().lower() # strip() removes any spaces before or after user input
if ans == 'c':
chart()
print()
print(Fore.GREEN + ' Continue? Y or N : ', end='')
ans = input().strip().lower() # strip() removes any spaces before or after user input
if ans == 'y': # shorter version 'continue Y or N' after printing breaker chart
main()
else:
print()
print(Fore.MAGENTA + ' Departing -' + Fore.GREEN + ' *** BREAKERVILLE ***')
playsound('train whistle.wav')
time.sleep(2) # delay to exit program
sys.exit()
elif ans != 'y':
print()
print(Fore.MAGENTA + ' Good Day -' + Fore.GREEN + ' *** BREAKERVILLE ***')
playsound('train whistle.wav') #CURRENTLY USING
time.sleep(2) # delay to exit program
sys.exit()
else:
main()
main()
For the records: The issue is fixed by providing full path to the sound file.
This is probably linked to the implementation of playsound and how it determines what is the current working directory. Please refer to https://pyinstaller.readthedocs.io/en/stable/runtime-information.html#run-time-information for a better understanding of that topic with pyinstaller

Get number first and second and third from text line

I have the following format in my txt file:
1 1,30705856804525E-7 2,64163961816166E-8
1,12201845645905 1,24157281788939E-7 2,45690063849224E-8
1,25892543792725 1,18248813407718E-7 2,29960868125545E-8
1,41253757476807 1,13006606738963E-7 2,16654658657944E-8
1,58489322662354 1,0842624220686E-7 2,05472137082552E-8
1,77827942371368 1,04479198625995E-7 1,96135836461053E-8
1,99526226520538 1,01119816520168E-7 1,8839035220708E-8
2,23872113227844 9,82917924829962E-8 1,82003176973922E-8
2,51188635826111 9,59338279926669E-8 1,76765304615856E-8
2,81838297843933 9,39840489877497E-8 1,72491425587395E-8
3,16227769851685 9,23831819932275E-8 1,69019571671924E-8
3,54813385009766 9,10766573269939E-8 1,66210121221866E-8
3,98107171058655 9,00157104410937E-8 1,63944182673958E-8
4,46683597564697 8,91577514039454E-8 1,62121711611007E-8
5,01187229156494 8,8466336478632E-8 1,60659361370108E-8
5,6234130859375 8,7910699164695E-8 1,59488209305891E-8
6,30957365036011 8,74651959748007E-8 1,58551749507296E-8
7,07945775985718 8,71086527354237E-8 1,57803938805046E-8
7,94328212738037 8,68237393092386E-8 1,57207402651238E-8
8,91250896453857 8,65963372120859E-8 1,56731942979604E-8
10 8,64150138113473E-8 1,56353241465013E-8
11,2201843261719 8,62705391568852E-8 1,5605175818223E-8
I need to get only value for integers on left and right value so in this example I need to get:
1
2,64163961816166E-8
10
1,56353241465013E-8
This is what I've tried:
' Check Noise Spectral Density.txt exists
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(fso.GetParentFolderName(WScript.ScriptFullName) + "\Projects\Noise Spectral Density.txt")) Then
' Open the file for input.
Set NoiseSpectralDensity = fso.OpenTextFile(fso.GetParentFolderName(WScript.ScriptFullName) + "\Projects\Noise Spectral Density.txt", 1)
' Noise Variables
Dim Noise
' Read from the file and display the results.
Do While NoiseSpectralDensity.AtEndOfStream <> True
' Read Line By Line
TextLine = NoiseSpectralDensity.ReadLine
' Check If Number
'If (IsNumeric(Left(TextLine, 5))) Then
' Get Noise
' Noise # 1kHz
Noise = Right(TextLine, InStr(Mid(TextLine, 2), InStr(TextLine, " ")-1))
x = MsgBox("SNR: " & Split(Left(TextLine, 5), " ")(0) & " NOISE: " & Noise & "",0, "Noise Spectral Density")
'End If
Loop
' Close the file for input.
NoiseSpectralDensity.Close
Else
x = MsgBox("Noise Spectral Density.txt NOT Found!" & vbCrLf & "Wave->Save As Text...", 0, "Noise Spectral Density")
End If
But I could not get left and right numbers in VBScript using Split(TextLine, " ")(0).
Your data seems to be tab-separated, so you could do something like this:
arr = Split(TextLine, vbTab)
If Not (InStr(arr(0), ",") > 0) Then
'first number doesn't have decimals
snr = arr(0)
noise = arr(2)
End If
Though the solution provided by #AnsgarWiechers should work but in case, if it doesn't, you can make use of regular expressions(Replace the whole Do-while loop with the following):
Set objReg = New RegExp
objReg.Pattern = "^(\d+)(?=\s).*\s+([\d,Ee-]+)$" 'See the explanation below
Do While NoiseSpectralDensity.AtEndOfStream <> True
'Read Line By Line
TextLine = NoiseSpectralDensity.ReadLine
' Check If Number
Set objMatches = objReg.Execute(TextLine)
For Each objMatch In objMatches
SNR = objMatch.submatches.item(0)
Noise = objMatch.submatches.item(1)
MsgBox "SNR: "&SNR&"; Noise: "&Noise
Next
Loop
Click for Regex Demo
Regex Explanation:
^ - asserts the start of the string
(\d+) - matches 1+ occurrences of a digit and captures it in Group 1
(?=\s) - positive lookahead to find the position immediately preceded by a white-space. So the digits in the step 2 will be matched until a whitespace(spaces,tabs etc.) is encountered
.* - matches 0+ occurrences of any character except a newline
\s+ - matches 1+ occurrences of a whitespace
([\d,Ee-]+) - matches 1+ occurrences of a digit or , or - or the letter E or e and capture it in group 2
$ - asserts the end of the string

I want to know the approach to compress any string

I want to know approach about, how can I compress the string like if I given some string ABCABCABC than as I am thinking that I can find sub-string as ABC which is frequently occurs so it will be compressed as 3ABC. Another way if string like ABCABCBC is given than here ABC is the frequently occurring sub-string, so it compressed as 2ABC1BC. As you can see I am taking only consideration of adjacent substrings.
s='FLFLAFLAFLAF'
def check(str_check,str):
try:
index=str.index(str_check)
except Exception:
index=9999
return index
def max_index(i,j,sub_str):
if(i>=0 and j<=len(count)):
try:
j=count.index(max(count[i:j]))
except Exception:
j=-1
try:
sub_str_index=int(sub_str.index(sub_list[j]))
except Exception:
sub_str_index=-1
temp=int(count[j])
if len(sub_str)==0:
return ""
elif(count[j]==1 or int(count[j])*len(sub_list[j])>len(sub_str)):
for i in range (len(sub_str)):
count[j+i]=0
return "1"+ sub_str
else:
#count[j]=0
return max_index(0,sub_str_index,sub_str[0:sub_str_index]) + str(temp) + sub_list[j] + max_index(len(sub_str[0:sub_str_index])+(int(temp)*len(sub_list[j])),len(sub_str),sub_str[len(sub_str[0:sub_str_index])+(int(temp)*len(sub_list[j])): len(sub_str)])
sub_list=sorted(set([s[i:i+j] for j in range(1,len(s)+1) for i in range(len(s)-j+1)]))
length=len(s)
length1=len(sub_list)
count=[]
for i in range (length1):
cnt=0
j=0
while(j<length):
k=check(sub_list[i],s[j:])
if k==9999:
break
if (s[j+k:j+k+len(sub_list[i])]==sub_list[i]):
if(cnt>=1 and s[j+k-len(sub_list[i]):j+k]==sub_list[i]):
j=j+k+1
cnt=cnt+1
elif (cnt==0):
j=j+k+1
cnt=cnt+1
else:
j=length
else:
j=length
count.append(cnt)
print "SUBLIST"
print sub_list
print "count"
count1=count
print count1
j=len(count)
i=0
max_ele=max(count)
while(max_ele in count):
max_in=count.index(max(count[i:j]))
print max_index(i,j,s)
count=count1
count[max_in]=0

File writing : carriage return and Tab

Hi i'm new to VB6 and i want to implement this : when a user is logged he enters his name and password , i should write it in a file.
Here's the file "authentification.txt" : it has the form of username password
bill hope
jessica 1234567
jhon 7654321
Here's the code :
Open "c:\authentification.txt" For Binary As #1
x = txtidentifiant.Text
y = txtmotdepasse.Text
Do While Not EOF(1)
Line Input #1, l
If l <> " " Then
Put 1, i, x & vbNewLine
Put 1, i + 1, y & vbNewLine
Else
//here i want to implement a carriage return in the file #1
End If
Loop
My problem is :that the file if filled like this : bhope
and it writes only the first line
You should use the Input and Print statements. They read and write comma delimited files, and are designed to be used in pairs, for just such an application.
Here's the new code :
Open "c:\authentification.txt" For Append As #1
x = txtidentifiant.Text
y = txtmotdepasse.Text
Print #1, x
Print #1, y
Close #1

Is there a SnakeYaml DumperOptions setting to avoid double-spacing output?

I seem to see double-spaced output when parsing/dumping a simple YAML file with a pipe-text field.
The test is:
public void yamlTest()
{
DumperOptions printOptions = new DumperOptions();
printOptions.setLineBreak(DumperOptions.LineBreak.UNIX);
Yaml y = new Yaml(printOptions);
String input = "foo: |\n" +
" line 1\n" +
" line 2\n";
Object parsedObject = y.load(new StringReader(input));
String output = y.dump(parsedObject);
System.out.println(output);
}
and the output is:
{foo: 'line 1
line 2
'}
Note the extra space between line 1 and line 2, and after line 2 before the end of the string.
This test was run on Mac OS X 10.6, java version "1.6.0_29".
Thanks!
Mark
In the original string you use literal style - it is indicating by the '|' character. When you dump your text, you use single-quoted style which ignores the '\n' characters at the end. That is why they are repeated with the empty lines.
Try to set different styles in DumperOptions:
// and others - FOLDED, DOUBLE_QUOTED
DumperOptions.setDefaultScalarStyle(ScalarStyle.LITERAL)

Resources