Word in list and an error if not - python-3.4

Hi what does %s mean in this code? I have never seen it before so its confusing to me.
sentance = input("Type in your sentance")
lower = sentance.lower()
text = lower.split()
Word = input("What word would you like to find?" ).lower()
position = 1
result = ""
for word in text:
if (word == Word):
if result == "":
result = result + str(position)
else:
result = result + "," + str(position)
position = position+1
if result!= "":
print("The word %s is in position/s %s" % (Word,result))
else:
print('word not found')
Need as soon as possible
Thanks!

this will work for you:
sentance = input("Type in your sentance\n")
lower = sentance.lower()
text = lower.split()
findWord = input("What word would you like to find?" ).lower()
position=1
result=""
for word in text:
if (word == findWord):
if result=="":
result=result+str(position)
else:
result=result+","+str(position)
position=position+1
if result!="":
print("The word %s is in positions. result %s etc.." % (findWord,result))
else:
print('word not found')

Related

Want to receive argument from user and put them on function

I want to get arguments from user and use them in function, but the types are different.
Note: a comment is there in bottom of code that is correctly work
but I want to get arguments directly
Thanks for your help
from string import ascii_letters
def encrypt(string , key):
alpha = ascii_letters
result = ''
for ch in string :
if ch not in alpha :
result += ch
else :
new_key = (alpha.index(ch) + key.str() ) % len(alpha)
result += alpha[new_key]
return result
def decrypt(string , key):
key *= -1
return encrypt(string , key)
state = ''
print("please enter 'e' to encrpyt & type 'd' to decrpyt :...")
state = input()
if state == 'e' :
print("please enter the str that you want to encrypt :... ")
c_str1 = input()
print("\nplease enter the key that shifts strings(e.x. 1 to 52):... ")
c_in1=input()
encrypt(c_str1, c_in1)
elif state == 'd':
print("please enter the str that you want to decrypt :... ")
c_str= input('')
print("\nplease enter the key (e.x. 1 to 52):... ")
c_in = input()
decrypt(c_str, c_in )
# print(decrypt('amir',4))
not sure what your question is , here my attempt at making your code run,
not sure runs as you expected:
from string import ascii_letters
def encrypt(string , key):
result = ''
alpha = ascii_letters
for ch in string :
if ch not in alpha :
result += ch
else :
new_key = (alpha.index(ch) + int(key)) % len(alpha)
result += alpha[new_key]
return result
def decrypt(string , key):
key *= -1
return encrypt(string , key)
state = ''
print("please enter 'e' to encrpyt & type 'd' to decrpyt :...")
state = input()
if state == 'e' :
print("please enter the str that you want to encrypt :... ")
c_str1 = input()
print("\nplease enter the key that shifts strings(e.x. 1 to 52):... ")
c_in1 = input()
print(encrypt(c_str1, c_in1))
elif state == 'd':
print("please enter the str that you want to decrypt :... ")
c_str = input()
print("\nplease enter the key (e.x. 1 to 52):... ")
c_in = int(input())
print(decrypt(c_str, c_in ))

xcom value are overwritten by else statement in if/else loop

I'm looping through a folder with some sql files. For each file I want to push them as xcom value with specific value for each queries.
The code below is kind of working however not when adding else statement. not set value is overwriting everything.
directory = r'airflow_home/dags/sql'
for filename in os.listdir(directory):
with open(os.path.join(directory, filename), 'r') as file:
sqlFile = file.read()
file.close()
if filename == 'api_params.sql':
query = sqlFile.format(partitioned_key,execution_date_second,partitioned_key,next_execution_date_second)
if filename == 'create_fact_table.sql':
query = sqlFile.format(fact_table_dest)
if filename == 'create_geo_table.sql':
query = sqlFile.format(fact_table_dest)
if filename == f'{geo_type}'+'.sql':
query = sqlFile.format(execution_date)
filename = 'geo_query'
if filename == 'schema_' + f'{schema}' + '.sql':
query = sqlFile.format(fact_table_dest,raw_table_dest,execution_date,next_execution_date)
filename = 'production_query'
if filename == 'insert_key.sql':
query = sqlFile.format(raw_table_dest,execution_date,next_execution_date)
else:
query = 'not set'
task_instance.xcom_push(key=filename, value=query)
can someone explain me what's happening here?
You are using multiple if statements, which are executed one after the other. The else just referring to the last if statement and therefore overwriting previous set query parameter. What you are actually looking for is elif - see Python Docs.
directory = r'airflow_home/dags/sql'
for filename in os.listdir(directory):
with open(os.path.join(directory, filename), 'r') as file:
sqlFile = file.read()
file.close()
if filename == 'api_params.sql':
query = sqlFile.format(partitioned_key,execution_date_second,partitioned_key,next_execution_date_second)
elif filename == 'create_fact_table.sql':
query = sqlFile.format(fact_table_dest)
elif filename == 'create_geo_table.sql':
query = sqlFile.format(fact_table_dest)
elif filename == f'{geo_type}'+'.sql':
query = sqlFile.format(execution_date)
filename = 'geo_query'
elif filename == 'schema_' + f'{schema}' + '.sql':
query = sqlFile.format(fact_table_dest,raw_table_dest,execution_date,next_execution_date)
filename = 'production_query'
elif filename == 'insert_key.sql':
query = sqlFile.format(raw_table_dest,execution_date,next_execution_date)
else:
query = 'not set'
task_instance.xcom_push(key=filename, value=query)

Encryption sorted...Decryption is close to finished - python 3.4.1

I can encrypt fine. That works will numbers, spaces and upper and lower case. However, when I set my code to decrypt the encrypted message, the code, for some reason, thinks that the decrypted message is empty. It prints an empty space. I'm not explaining it very well, but if you run the code you will understand what I am on about. If you have any ideas, please let me know.
alphabetL = 'abcdefghijklmnopqrstuvwxyz'
alphabetC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
number = '0123456789'
space = ' '
Ll = len(alphabetL)
Lc = len(alphabetC)
Ln = len(number)
Lall = Ll + Lc + Ln
Question1 = input("Hello, please insert the message you want encrypted: ")
key1 = int(input("Please insert the key you want used [Keep between 1 and 26]: "))
cipher = ''
cipher2 = ''
for A in Question1:
if A in alphabetL:
cipher += alphabetL[(alphabetL.index(A)+key1)%Ll]
elif A in alphabetC:
cipher += alphabetC[(alphabetC.index(A)+key1)%Lc]
elif A in number:
cipher += number[(number.index(A)+key1)%Ln]
elif A in space:
cipher += space
else:
print ("Error, please use abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
print (cipher)
Question2 = input("Would you like to decrypt the message? [Y/N]: ")
if Question2 == "Y":
for A in cipher2:
cipher2 += cipher[(cipher(A)-key1)%(len(cipher))]
print (cipher2)

Need help assigning parameters to my definitions

My code works if I comment out my definitions but I need it to work with the definitions. I don't know which parameters I should assign to them to make the code work properly.
#def main():
phrase = input("Enter a phrase: ")
count = {}
print("Number of characters: ",len(phrase))
#def wordCount():
words = phrase.split()
wordCount = len(words)
print("Number of words: ",wordCount)
#def average():
avg = len(phrase)/wordCount
print("The average word length: %.01f" % avg)
#def freqWords():
freqLetter = phrase[0]
max = phrase.count(phrase[0])
for char in phrase:
if char is not " ":
if phrase.count(char) > max:
freqLetter = char
max = phrase.count(char)
print("The most frequent letter: ", freqLetter)
#main()
You can either make phrase, count, etc. as global variable or make them parameters in this case, here is how to do with passing parameters:
def main():
phrase = input("Enter a phrase: ")
print("Number of characters: ",len(phrase))
count = wordCount(phrase)
average(phrase,count)
freqWords(phrase)
def wordCount(phrase):
words = phrase.split()
wordCount = len(words)
print("Number of words: ",wordCount)
return wordCount
def average(phrase, wordCount):
avg = len(phrase)/wordCount
print("The average word length: %.01f" % avg)
def freqWords(phrase):
freqLetter = phrase[0]
max = phrase.count(phrase[0])
for char in phrase:
if char is not " ":
if phrase.count(char) > max:
freqLetter = char
max = phrase.count(char)
print("The most frequent letter: ", freqLetter)
main()

How to read text files that have line feed and carriage return intermixed using X++?

I am trying to read a text file using Dynamics AX. However, the following code replaces any spaces in the lines with commas:
// Open file for read access
myFile = new TextIo(fileName , 'R');
myFile.inFieldDelimiter('\n');
fileRecord = myFile.read();
while (fileRecord)
{
line = con2str(fileRecord);
info(line);
…
I have tried various combinations of the above code, including specifying a blank '' field delimiter, but with the same behaviour.
The following code works, but seems like there should be a better way to do this:
// Open file for read access
myFile = new TextIo(fileName , 'R');
myFile.inRecordDelimiter('\n');
myFile.inFieldDelimiter('_stringnotinfile_');
fileRecord = myFile.read();
while (fileRecord)
{
line = con2str(fileRecord);
info(line);
The format of the file is field format. For example:
DATAFIELD1 DATAFIELD2 DATAFIELD3
DATAFIELD1 DATAFIELD3
DATAFIELD1 DATAFIELD2 DATAFIELD3
So what I end up with unless I use the workaround above is something like:
line=DATAFIELD1,DATAFIELD2,DATAFIELD3
The underlying problem here is that I have mixed input formats. Some of the files just have line feeds {LF} and others have {CR}{LF}. Using my workaround above seems to work for both. Is there a way to deal with both, or to strip \r from the file?
Con2Str:
Con2Str will retrieve a list of values from a container and by default uses comma (,) to separate the values.
client server public static str Con2Str(container c, [str sep])
If no value for the sep parameter is specified, the comma character will be inserted between elements in the returned string.
Possible options:
If you would like the space to be the default separator, you can pass space as the second parameter to the method Con2Str.
One other option is that you can also loop through the container fileRecord to fetch the individual elements.
Code snippet 1:
Below code snippet loads the file contents into textbuffer and replace the carriage returns (\r) with new line (\n) character. The condition if (strlen(line) > 1) will help to skip empty strings due to the possible occurrence of consecutive newline characters.
TextBuffer textBuffer;
str textString;
str clearText;
int newLinePos;
str line;
str field1;
str field2;
str field3;
counter row;
;
textBuffer = new TextBuffer();
textBuffer.fromFile(#"C:\temp\Input.txt");
textString = textBuffer.getText();
clearText = strreplace(textString, '\r', '\n');
row = 0;
while (strlen(clearText) > 0 )
{
row++;
newLinePos = strfind(clearText, '\n', 1, strlen(clearText));
line = (newLinePos == 0 ? clearText : substr(clearText, 1, newLinePos));
if (strlen(line) > 1)
{
field1 = substr(line, 1, 14);
field2 = substr(line, 15, 12);
field3 = substr(line, 27, 10);
info('Row ' + int2str(row) + ', Column 1: ' + field1);
info('Row ' + int2str(row) + ', Column 2: ' + field2);
info('Row ' + int2str(row) + ', Column 3: ' + field3);
}
clearText = (newLinePos == 0 ? '' : substr(clearText, newLinePos + 1, strlen(clearText) - newLinePos));
}
Code snippet 2:
You could use File macro instead of hard coding the values \r\n and R that denotes the read mode.
TextIo inputFile;
container fileRecord;
str line;
str field1;
str field2;
str field3;
counter row;
;
inputFile = new TextIo(#"c:\temp\Input.txt", 'R');
inputFile.inFieldDelimiter("\r\n");
row = 0;
while (inputFile.status() == IO_Status::Ok)
{
row++;
fileRecord = inputFile.read();
line = con2str(fileRecord);
if (line != '')
{
field1 = substr(line, 1, 14);
field2 = substr(line, 15, 12);
field3 = substr(line, 27, 10);
info('Row ' + int2str(row) + ', Column 1: ' + field1);
info('Row ' + int2str(row) + ', Column 2: ' + field2);
info('Row ' + int2str(row) + ', Column 3: ' + field3);
}
}
Never tried to use the default RecordDelimiter as FieldDelimiter and not setting another RecordDelimiter explicitly. Normally rows (Records) are delimited by \n and fields are delimited by comma, tab, semicolon or some other symbol. You might also be hitting some weird behaviour when TextIO is assuming correct UTF-format. You didn't supply an example of some rows from you datafile, so guessing is hard.
Read more about TextIO here: http://msdn.microsoft.com/en-us/library/aa603840.aspx
EDIT:
With the additional example of file content, it seems to me the file is a fixed width file, where each column has its own fixed width. I would rather recommend using subStr if that is the case. Read about substr here: http://msdn.microsoft.com/en-us/library/aa677836.aspx
use StrAlpha to restrict blank values after you convert Con2Str

Resources