State name spellcheck code not working with two word state names - python-3.x

I am working on vetting someone else's state spellchecker. The test data they ran seemed to work fine, but trying a different data set, it doesn't seem to be able to get past the first word "North" in a state name.
I need the code to be able to work with state names with two words.
This is the code:
import sys
!pip install pyspellchecker
from spellchecker import SpellChecker
#from google.colab import files
import pandas as pd
import io
#Implement spellcheck.
spell=SpellChecker()
for ind in newDF.index:
stateWordList = newDF['State'][ind].split()
if len(stateWordList) == 1:
#print(True)
if stateWordList[0] in spell:
pass
else:
correctState = input("'{}' is not a valid state, please enter a correct spelling:".format(stateWordList[0]))
newDF.at[ind, 'State'] = correctState
else:
misspelledState = False in (stateWord in spell for stateWord in stateWordList)
if misspelledState == True:
pass
else:
correctState = input("'{}' is not a valid state, please enter a correct spelling:".format(stateWordList[0]))
newDF.at[ind, 'State'] = correctState
Instead, it isn't seeing North WhateverState as valid, and returns:
'North' is not a valid state, please enter a correct spelling:
Does it need a condition specifically for two word names?

In your else statement, you have a logic error
else:
misspelledState = False in (stateWord in spell for stateWord in stateWordList)
if misspelledState == True:
pass
else:
correctState = input("'{}' is not a valid state, please enter a correct spelling:".format(stateWordList[0]))
newDF.at[ind, 'State'] = correctState
Let's see misspelledState = False in (stateWord in spell for stateWord in stateWordList), if all the words in stateWordList is well spelled, you are checking with misspelledState = False in (True, True, ...), the result will be False.
Then go to the if-else condition, it will go to else condition where outputs the correction message:
if misspelledState == True:
pass
else:
correctState = input("'{}' is not a valid state, please enter a correct spelling:".format(stateWordList[0]))
newDF.at[ind, 'State'] = correctState
You can use
misspelledState = all([stateWord in spell for stateWord in stateWordList])

Related

regex doesn't seem to work in allowRegexes parameter when using pyinputplus

I am using pyinputplus and specifically inputNum
https://pyinputplus.readthedocs.io/en/latest/
This is what my code looks like:
msg = 'Enter value to add/replace or s to skip field or q to quit: '
answer = pyip.inputNum(prompt=msg, allowRegexes=r'^[qQsS]$', blank=False)
My goal is to allow any number but also allow one of the following q,Q,s,S.
However when I run the code and enter 'sam' the code crashes because later on I am trying to convert to float(answer).
My expectation is that allowRegexes will not allow this and will show me the prompt again to re-enter.
Please advise!
It seems pyip.inputNum stops validating the input if you provide allowRegexes argument. See the allowRegexes doesn't seem work properly Github issue.
You can use the inputCustom method with a custom validation method:
import pyinputplus as pyip
import ast
def is_numeric(x):
try:
number = ast.literal_eval(x)
except:
return False
return isinstance(number, float) or isinstance(number, int)
def raiseIfInvalid(text):
if not is_numeric(text) and not text.casefold() in ['s', 'q']:
raise Exception('Input must be numeric or "q"/"s".')
msg = 'Enter value to add/replace or s to skip field or q to quit: '
answer = pyip.inputCustom(raiseIfInvalid, prompt=msg)
So, if the text is not and int or float and not equal to s/S/q/Q, the prompt will repeat showing up.

cant get my while loops working the way i want it to

i am trying to get this code to work properly where if you input a number it will revert you back to the name=input prompt and once you enter alphabetical characters and not numerical characters it will allow you to move on to the next set of code but it keeps returning you to the name = input and doesnt let you through the rest of the code
def setup():
global name
global HP
global SP
global MP
while True:
try:
name = input('can you please tell me your name? ')
name2=int(name)
if not name.isalpha==True and not name2.isdigit==False:
break
except Exception:
print('please input your name')
continue
HP = randint(17,20)
SP = randint(17,20)
MP = randint(17,20)
print('welcome ['+name+':]: to the moon landing expedition')
There is a problem at name2=int(name) This causes an exception unless you type all numbers. In turn, this triggers the Exception and loops it forever. Your while loop seems fine.
What i think you should do:
while True:
name = input('What is your name')
isnum = False
for i in name:
if i.isnumeric():
isnum = True
break
if isnum:
print('Please type your name.')
continue
break

telethon events wont get specific user's events

So i've been working on this script for few days now and the script seems to run correctly without getting any errors but the issue is that my point of the script is getting specific user's status changes and instead of that the script prints me everytime ANYONE from my contants changes they're status inculding myself.
Please, does anyone think he can assist me ? I have been stuck on it for too long now and I am really desprate make that script works..
By the way, I was adding print(client.user_id) just to see if it works and I received the User ID of anyone in my contacts who made some kind of action.
from telethon.tl.types import UserStatusOffline
from telethon.sync import TelegramClient
from telethon import events
from datetime import datetime
import time
### Client Side ###
target = ""
phone = "+"
api_id =
api_hash = ""
client = TelegramClient(phone, api_id, api_hash)
client.start()
if client.is_user_authorized():
print(f"Session started at : {datetime.now()}")
time.sleep(2)
print("Logging in to Telegram complete.")
time.sleep(2)
else:
client.send_code_request(phone)
client.sign_in(phone, input('Enter the code: '))
print(f"Started listening to {target}'s status...")
time.sleep(2)
target_id = client.get_peer_id(target)
print(f"{target}'s User ID is : {target_id}")
time.sleep(2)
############################################
# First status check to see rather #
# the user is correctly online or not #
# once it prints hes correct statement #
# global value will be changed so it wont #
# be printed again and again. #
############################################
first_msg = False
async def first_con():
if first_msg == False:
account = await client.get_entity(target)
if isinstance(account.status, UserStatusOffline):
print(f"{target} is correctly Offline.")
first_msg = True
else:
print(f"{target} is correctly Online.")
first_msg = True
else:
print("Something went wrong checking correct status.")
##################EVENTS####################
# Only events thats occurred after script #
# first run will pop up with prints ! #
# Every event that doesn't come from the #
# target gets as "event from username" #
############################################
#client.on(events.UserUpdate())
async def handler(event):
await first_con()
time.sleep(2)
if event.user_id == target_id:
if event.online:
print(f"{target} went Online at : {datetime.now()}")
elif event.recently:
print(f"{target} was recently online at : {datetime.now()}")
elif event.typing:
print(f"{target} typed a message at : {datetime.now()}")
else:
print("Sorry there was an error.")
else:
#print("Event from non-intersting user.") debugging propuses only
client.run_until_disconnected()
Let's zoom in on the code:
#client.on(events.UserUpdate())
async def handler(event):
x = await client.get_entity(target)
target_id = x.id
event.input_user = target_id
if event.input_user == target_id:
Let's tear it apart:
event.input_user = target_id
if event.input_user == target_id:
Let's give it different names. event.input_user will be foo and target_id will be bar:
foo = bar
if foo == bar:
You just assigned a value to the first variable, and are then comparing the first variable to that same value. Of course, this is always True, for any foo and bar values.
Modifying the event is generally a bad idea and I'm not sure what your intention was, but it seems to me that you should be caching the integer ID and then comparing that instead of making the call to get_entity every time (because input_user is a InputPeerUser and won't compare with User, which is why I guess you tried the weird assign):
target_id = client.get_peer_id(target)
#client.on(events.UserUpdate)
async def handler(event):
if event.user_id == target_id:
...
This way only one call is made at most, and you compare integers which is fast. Make sure to check the documentation on UserUpdate for more information.

Python 3 How to Ask user for specific input and reject invalid inputs

I have a question on how to check a user's input and make sure they are returning a specific string. Currently, the function when called will ask the user for their input. However, if they choose a string that is not part of the function, the else statement will execute and continue the code. I am trying to figure out how to loop this function, until a user inputs one of the strings that the function is looking for. Can anyone help me with this? I am new to python and would appreciate any help.
def dwarf_class_definer(dwarf_class):
if dwarf_class == "Thane":
print("'Ahhh Nobility'")
elif dwarf_class == "Mekanik":
print("'Interesting a Mechanic'")
elif dwarf_class == "Ancestrite":
print("'A spiritualist. I see...'")
elif dwarf_class == "Prisoner":
print("'Never met a gen-u-ine 'Last chancer.'")
elif dwarf_class == "Civilian":
print("'ehhh a civilian? Wut you doing here?'")
else:
print("You aren't choosing a valid class.")
dwarf_class = input("Which Class will you choose?: ")
dwarf_class_definer(dwarf_class)
A while loop will keep going until you tell it not to anymore. You can see when an expected value is supplied, the break command will terminate the while loop. A dictionary can also make your code a lot cleaner and easier to maintain compared to a bunch of if statements.
dwarf_classes = {
"Thane": "'Ahhh Nobility'",
"Mekanik": "'Interesting a Mechanic'",
"Ancestrite": "'A spiritualist. I see...'",
"Prisoner": "'Never met a gen-u-ine 'Last chancer.'",
"Civilian": "'ehhh a civilian? Wut you doing here?'",
}
while True:
dwarf_class = input("Which Class will you choose?: ")
if dwarf_class in dwarf_classes.keys():
print(dwarf_classes[dwarf_class])
break
print("You aren't choosing a valid class.")
example:
$ python3 so.py
Which Class will you choose?: Python!
You aren't choosing a valid class.
Which Class will you choose?: Prisoner
'Never met a gen-u-ine 'Last chancer.'

why doesn't the highlighted section of code work and what do i need to change to make it able to work

I just deleted my previous question as someone made it embarrassingly obvious that I didn't ask an actual question with a main goal.I apologise for this.
I am only referring to the last part of the code. The "A" option as i cannot figure out why it is incorrect
The full thing works other than the A section it says there is a syntax error. That's it.
I've tried re placing the brackets and playing around with them and so on.
def Jobs():
def Parse_Line(Job_Line):
Job_Line = Job_Line.strip()
Estimate_Number, Estimate_Date, Customer_ID, Final_Total, Job_Status,Amount_Pay= Job_Line.split(",")
Painting_Job = {
'Estimate_Number':Estimate_Number,
'Estimate_Date':Estimate_Date,
'Customer_ID':Customer_ID,
'Final_Total':Final_Total,
'Job_Status':Job_Status,
'Amount_Pay':Amount_Pay,
}
return Painting_Job
Job_List = []
with open("paintingJobs.txt", "r") as Painting_Jobs:
for line in Painting_Jobs:
Job_List.append(Parse_Line(line))
return Job_List
def Accepted(job):
return job['Job_Status'] == "A"
def Outstanding(job):
return int(job['Final_Total']) - int(job['Amount_Pay'])
Job_List = Jobs()
print ("\nOption A: Search for an estimate\n\nOption B: Dislay the outstanding payments\n\nOption C: Display your total revenue\n\nOr Press Q to quit")
Option_Choice = input("Which option do you want to do?")
if Option_Choice == "A" or Option_Choice == "a":
Estimate_no = input("Please enter the required estimate number so we search our database: ")
Estimate_Found = Estimate_no
job in Job_List if ['Estimate_Number'] == Estimate_no
if Estimate_Found:
print (Estimate_Found)

Resources