checking a word in the text and print() a command once - python-3.x

Using these commands I get the three sentences.
AnyText = driver.find_elements_by_xpath('AnyXpath')
for AnyText1 in AnyText:
print(AnyText1.text)
In the console, I get something like that:
**
1) Hello my name is John
**
2) Hello my name is Mark
**
3) Hello my name is Alex..
How can I check that all three sentences have the word "name"
and print("OK") if the word is in the sentence (element) and print("ERROR") if not.
Im try:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
if all(Text in AnyText1 for two in AnyText1):
print('OK')
else:
print('ERROR')
but this method only checks the first element (first sentence). I also tried something like this
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
for AnyText1 in AnyText:
if all(Text in AnyText1):
print('OK')
else:
print('ERROR')
but I get many times OK or ERROR
UPD:
With a question on the text, I figured out with your help. Now I want to understand the numbers)
I have a loop that checks the next number more or less. If more, writes ERROR, if less, writes OK
sort_month=driver.find_element_by_xpath('/html/body/div[6]/div[2]/div/div[1]/div/div[13]/table/thead/tr/th[3]/a[4]').click()
month2=driver.find_element_by_xpath('//*[starts-with(#id, "td_")]/td[3]/span[3]')
month2=month2.text.replace("'", "").replace(" ", "")
buffer = 0
if int(month2) > buffer:
print()
buffer = int(month2)
month1=driver.find_elements_by_xpath('//*[starts-with(#id, "td_")]/td[3]/span[3]')
for spisok_month in month1:
spisok_month = spisok_month.text.replace("'", "").replace(" ", "")
if int(spisok_month) > buffer:
print('ERROR')
elif int(spisok_month) < buffer:
print('OK')
else:
print('==')
buffer = int(spisok_month)
here I would also like to see OK or ERROR only once.
Any ideas?

The problem seems to be with the short form for loop in your first snippet. Basically it should look like the below:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
if all(Text in AnyText1.text for AnyText1 in AnyText):
print('OK')
else:
print('ERROR')
UPDATE:
On the updated part of your question, this is a different implementation as you have to update the condition in each iteration. For readability, it probably makes sense to keep this expanded:
outcome = 'OK'
for spisok_month in month1:
spisok_month = spisok_month.text.replace("'", "").replace(" ", "")
if int(spisok_month) > buffer:
outcome = 'ERROR'
elif outcome == 'OK' and int(spisok_month) == buffer:
outcome = '=='
buffer = int(spisok_month)
print(outcome)
Note: The update is almost a separate question. this means that either your first question was not representative of the actual problem or you should ask in a separate post

In you code AnyText1 is a WebElement, not a text. You should use AnyText1.text to get text and then it will work:
AnyText = driver.find_elements_by_xpath('AnyXpath')
Text = 'name'
# AnyText1 is a WebElement and you should get text
if all(Text in AnyText1.text for AnyText1 in AnyText):
print('OK')
else:
print('ERROR')
Please check coding conventions to improve code style.

Related

Parsing multiple lines from user input

I am trying to streamline a process to generate some reports. Right now, users have to enter information into several prompts. To speed things up, I was curious if it's possible to parse multiple lines from user input. Basically, just copy all of the writeups and paste them in the terminal and have it parsed out, then boom, report. An example of what they would input is shown below:
number
title
string
string(tags)
A brief summary of what is being researched
sources
Ideally, after the input is accepted, I would store each line in a temp variable then concat them and store them in a single list entry. That would look like this:
[(number,title,string,string(tag),A brief summary of what is being researched,source),(entry2),(entry3),etc...]
Ive pasted some the working code below that will accept multiple lines until a blank character is seen:
end_of_art = ""
while True:
line = input()
if line.strip() in end_of_art:
break
text += "s," % line
UPDATE
So I was able to get it working the way I needed, but now I am getting this empyt string added to the end of my list.
Heres the new working code:
a_sources = {}
text = ""
while True:
line = input()
if not line.strip():
articles.append(text)
break
elif "//end//" in line:
text += "%s" % a_sources
articles.append(text) #append to articles list
text = "" #clear the temp text var
a_sources = {} #clear source dict var
elif validators.url(line):
atemp = validate_source(extract(line).domain)
a_sources.update({atemp:line})
#text += "%s," % a_sources
elif line:
text += "%s," % line
Output:
["1,Title 1,string,Tags,This is just junk text,{'Google': 'http://google.com'}", '']
You could go by some sort of looping input. EX:
user_inputs = []
recent_input = None
while recent_input != "":
recent_input = str(input())
user_inputs.append(recent_input)
The catch is is that you input would need an empty line at the end of it. So rather than:
"a"
"b"
"c"
You'd want:
"a"
"b"
"c"
""

Code not checking if inputted answer is correct

I am trying to create a multiple choice quiz that takes questions from an external .txt file and prints it in python. The text file is laid out like this:
1,Who was the first man to walk on the moon?,A.Michael Jackson,B.Buzz Lightyear,C.Neil Armstrong,D.Nobody,C
When I run the code and input the right answer it still says incorrect but continues to say the answer I inputted.
In the code I split each line in the text file by a ',' so the correct answer in the text file is always detail[6]. In the code I have put:
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I thought this would work as it is checking the inputted answer against detail[6] but it always comes out as incorrect.
import random
score=0
with open('space_quiz_test.txt') as f:
quiz = f.readlines()
questions = random.sample(quiz, 10)
for question in questions:
detail = question.split(",")
print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
print(" ")
answer=input("Answer: ")
while True:
if answer.upper() not in ('A','B','C','D'):
print("Answer not valid, try again")
else:
break
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I would like the code to be able to check if the inputted answer is correct by checking it against detail[6] within the text file, instead of always coming out as incorrect, the correct answer is detail[6].
The problem is that readlines() retains the newline character at the end of each line.
Your detail[6] is something like 'C\n' rather than 'C' itself. To fix that, use
detail = question.strip().split(",")

Struggling to reassemble jsonl from stream

I am trying to process jsonlines from an API and I am running into an issue where requests.iter_lines() is not timely. I have to now try to incorporate requests.iter_content(chunk_size=1024*1024). I am trying to work through the logic I would need to take an incomplete jsonline[1] and attach it to the next chunk_size so it makes a complete one.
My current attempt is running a series of if statements against to detect an undesirable state [2] and then rebuild it and continue process, but i'm failing to reassemble it in all the various states this could end up in. Does someone have an example of a well thought out solution to this problem?
[1]
Example:
Last item from first chunk:
{'test1': 'value1', 'test2': 'valu
first item from second chunk:
e2', 'test3': 'value3'}
[2]
def incomplete_processor(main_chunk):
if not main_chunk[0].startswith('{') and not main_chunk[-1].endswith('\n'):
first_line = str(main_chunk[0])
last_line = str(main_chunk[-1])
main_chunk.pop(0)
main_chunk.pop(-1)
return first_line, last_line
if not main_chunk.startswith('{') and main_chunk[-1].endswith('\n'):
first_line = str(main_chunk[-1])
main_chunk.pop(0)
return first_line
if main_chunk.startswith('{') and not main_chunk[-1].endswith('\n'):
last_line = str(main_chunk[-1])
main_chunk.pop(-1)
return last_line
I solve this problem by converting my original rsplit('\n') into a deque and then caught any valueerrors raised as a result of the incomplete json. I stored the first value that errors out, waited for the next value to error out and then combined them.
while True:
try:
jsonline = main_chunk_deque.popleft()
jsonline = json.loads(jsonline)
except ValueError as VE:
if not jsonline.endswith('}'):
next_line = jsonline
elif not jsonline.startswith('{'):
first_line = jsonline
jsonline = json.loads(next_line + first_line)
continue
except IndexError:
break

How do you report duplicates in a txt. file?

In our class we were given the task to basically create a program that re-enacts the US election last year. One of the extra challenges is that when you enter an ID number that is already in the file, it should come up with an error and just stop. However, when I try to execute this code, it comes up with
ValueError: I/O operation on closed file.
This is the code I've done so far...
ID = input("Please input ID code ")
if(len(ID)) == 6:
print("ID length: Valid")
N += 1
else:
print("ID Code: Error")
sys.exit()
with open('ID.txt', 'a') as idc:
idc.write(ID + ' ')
already_seen = set()
for line in idc:
if line not in already_seen:
print("Valid")
else:
print("Error")
sys.exit()
Thanks
You should know the difference between the
with open('ID.txt', 'a') as idc:
do sth
and the
idc = open('ID.txt', 'a')
In the first case, after the do sth finished, the __exit__() of the idc will be called to close the file object.
I advise you to use the second expression that I indicate above. If you are new to Python, this blog will help you to understand the detail reasons.

Creating a autocorrect and word suggestion program in python

def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
while (user_input == ""):
user_input = input("key in word you wish to enter: ")
user_word = autocorrect(user_input).replace(' ', '')
with open('big.txt') as myFile:
for word in myFile:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
Basically when I had a dictionary of correctly spelled word in "big.txt", if I get the similar from the user input and the dictionary, I will print out a line
I am comparing between two string, after I sort it out
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
When I try hard code with other string like
if ("a" == "a"):
print("The word",user_input,"exist in the dictionary")
it worked. What wrong with my code? How can I compared two string from the file?
What does this mean? Does it throw an exception? Then if so, post that...
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
because I can run a version of your program and the results are as expected.
def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
#while (user_input == ""):
user_input = raw_input("key in word you wish to enter: ").lower()
user_word = autocorrect(user_input).replace(' ', '')
print ("user word '{0}'".format(user_word))
for word in ["mike", "matt", "bob", "philanderer"]:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
key in word you wish to enter: druge
user word 'degru'
The word druge doesn't exist in the dictionary
key in word you wish to enter: Mike
user word 'eikm'
('The word','mike', 'exist in the dictionary')
Moreover I don't know what all this "autocorrect" stuff is doing. All you appear to need to do is search a list of words for an instance of your search word. The "sorting" the characters inside the search word achieves nothing.

Resources