How to past Check 50 for Bleep.py in Pset 6? - python-3.x

The number of "*" printed fluctuates according to the length of string entered
def main():
# check command line argument
if len(argv) != 2:
print("Usage: python bleep.py dictionary")
exit(1)
else:
ban = set()
# Load txt file
with open(argv[1], "r") as f:
for line in f:
# strip the space and add to set
ban.add(line.strip())
# prompt user input
input = get_string("What message would you like to censor?\n")
# Split input into word tokens
token = input.split()
censored_msg = ""
for i in token:
if i.lower() in ban:
censored_msg = (censored_msg + "*"*(len(token)+1) + " ")
else:
censored_msg += i + " "
# print censored message
print(censored_msg.strip())
if __name__ == "__main__":
main()
It prints fine for some cases, such as
Input: heck my gosh
Output: **** my ****
But not so in others (should be **** ****)
Input: heck gosh
Output: * * (just 6 * for 8 letters)

Is it a typo? Check this line very carefully
censored_msg = (censored_msg + "*"*(len(token)+1) + " ")
and remember which is what here for i in token:

Related

Program doesn't work if fed with a large amount of data

#This program takes in a text file and whatever the ser types in ; it searches for the specific word or phrase and then print out in which line this word or phrase is located .
If i feed it a text file with 20 lines , it produces normal results
As soon as i give it a 3000 worded document it produces error
Can anyone explain this
while True:
search = str(input("==>"))
line_number = 1
fslope = open("searching_in_a_textfile")
for line in fslope:
if search.lower() in line:
print("tHE LINE NUMBER IS ", line_number)
print("THE LINE SAYS : " + line)
line_number = line_number + 1
continue
if search.upper() in line:
print("tHE LINE NUMBER IS ", line_number)
print("THE LINE SAYS : " + line)
line_number = line_number + 1
continue
if search.title() in line:
print("tHE LINE NUMBER IS ", line_number)
print("THE LINE SAYS : " + line)
line_number = line_number + 1
continue
else:
line_number = line_number + 1
continue
print("END OF PRIOCESS")
First lets make it simple: (this code is almost the same as yours)
lines = []
with open('searching_in_a_textfile') as f:
lines = f.readlines()
while True:
search = input('==>')
if not search:
break
for line_number, line in enumerate(lines, 1):
if search.lower() in line.lower():
print('tHE LINE NUMBER IS ', line_number, '\nTHE LINE SAYS :', line)
print("END OF PRIOCESS")
Now when the input is '' (empty string / no input) the process will stop.
if you can add your error it could be very helpful.

missing one thing to complete problem set 6 cs50

here are the instructions: https://docs.cs50.net/2019/x/psets/6/index.html
I almost finish it but the problem is that the last character of the sentence is a space because of the end=" " and that is th error, but i dont know how to solve it because if i delete the end=" " all the words in the sentence will be togheter because there are not spaces. What should i do?
Here is my code
from cs50 import get_string
from sys import argv
def main():
if len(argv) != 2:
print("Error")
exit(1)
wordsbanned = set()
mayuscula = set()
file = open(argv[1], "r")
for line in file:
wordsbanned.add(line.rstrip("\n"))
file.close
message = get_string("Enter a message: ")
token = message.split()
for word in wordsbanned:
x = word.upper()
mayuscula.add(x)
for t in token:
if t in wordsbanned or t in mayuscula:
print(("*" * len(t)), end=" ")
else:
print(t, end=" ")
if __name__ == "__main__":
main()
What is the opposite of split as used here token = message.split()? It is join. What if you stored tokens in a list instead of printing them? Then you could use join to turn the result into a string.

TypeError: missing 1 required positional argument: 'value'

experts
I meet an value missing error in my code , but I think the variable in function are claimed. I don't know why it is happens.
$ python check_rsg_V0312.py
2018-03-20 13:05:49 === Script Start ===
2018-03-20 13:05:49 Monitoring via remote logon
The authenticity of host 'rpahost0 ([127.0.0.1]:7000)' can't be established.
RSA key fingerprint is 2d:f5:67:75:84:b6:24:45:e6:48:60:65:61:ca:69:f7.
Are you sure you want to continue connecting
(yes/no)? yes
Warning: Permanently added 'rpahost0' (RSA) to the list of known hosts.
Password:
Traceback (most recent call last):
File "check_rsg_V0312.py", line 89, in <module>
label = ssh_cmd(nLocalport, rsg_target, ouser, lookip, opasw, command,)
File "check_rsg_V0312.py", line 79, in ssh_cmd
print (ssh.before.decode(),ssh.after().decode())
TypeError: __init__() missing 1 required positional argument: 'value'
Below is my code, it is really strange that one error happens in ssh_cmd
function. detailed please review comments in code.
import os,time,pexpect,re, subprocess, smtplib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
#-----------------------------------------
dir = os.environ['HOME']
ouser = 'x02d726'
opasw = 'qwe12'
nLocalport = 7000
lookip = '127.0.0.1'
rsg_target = "rpahost0"
command = "ls -ltrh | grep tunnel | tail"
nstage = 0
mail_addr = 'cheng.huang#qq.com'
otp_file = dir + '/otplist/C591260'
otp_list = []
rsg_file = dir + '/.rsg_hosts'
known_hosts = dir + '/.ssh/known_hosts'
rsg_port = "auto"
#-----------------------------------------
def printlog(prompt):
year, mon, mday, hour, min, sec, wday, yday, isdst = time.localtime()
print("%04d-%02d-%02d %02d:%02d:%02d %s" % (year, mon , mday, hour, min,
sec, prompt))
def get_egw_name(ref_arr, key):
for oneline in ref_arr:
if (re.search(key, oneline)):
templine = oneline
oneline = re.sub('^\s+|\s+$','',oneline)
egw_ssg = re.split('\s+',oneline)[2]
result = re.split(':',egw_ssg)[0]
return result
def sendworker(to_addr):
from_addr = 'itk-bj.ericsson.se'
smtp_server = 'smtp.eamcs.ericsson.se'
msg = MIMEText('There is no otp left ,please input new OTP list',
'plain', 'utf-8')
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = Header(u'OTP List is Blank', 'utf-8')
server = smtplib.SMTP(smtp_server, 25)
#server.set_debuglevel(1)
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
def ssh_cmd(port, target, user, ip, pasw, cmd ):
printlog("=== Script Start ===")
printlog("Monitoring via remote logon")
time.sleep(1)
ssh = pexpect.spawn('/usr/bin/ssh -p %s -o HostKeyAlias=%s %s#%s %s' %
(port, target, user, ip, cmd ),timeout=6000)
try:
i = ssh.expect(['Password: ', 'continue connecting (yes/no)?'],
timeout=15)
if i == 0 :
print(ssh.before.decode(),ssh.after.decode())
ssh.sendline(pasw)
elif i == 1:
print(ssh.before.decode(),ssh.after.decode())
ssh.sendline('yes')
ssh.expect('Password: ')
print(ssh.before.decode(),ssh.after.decode())
ssh.sendline(pasw)
except pexpect.EOF:
print ("no connection EOF,please check RSG tunnel")
except pexpect.TIMEOUT:
print ("your pexpect has TIMEOUT")
else:
ssh.expect(pexpect.EOF)
print (ssh.before.decode(),ssh.after().decode()) # if I disable this line, there will be no error.
flag = ssh.before.decode()
return flag
ssh.close()
if __name__ == '__main__':
if os.path.exists(os.environ['HOME'] + "/.ssh/known_hosts"):
os.remove(known_hosts)
else:
pass
label = ssh_cmd(nLocalport, rsg_target, ouser, lookip, opasw, command)
if re.search('tunnel_check', str(label)):
nstage = 1
if (nstage == 0):
printlog("Tunnel was down and will re-establish now\n")
rsg = open (rsg_file,'r')
rsg_in = rsg.readlines()
rsg.close()
egwname = get_egw_name(rsg_in, rsg_target)
try :
otp = open(otp_file, 'r')
otp_arrary = otp.readlines()
otp.close()
for ot in otp_arrary:
ot = ot.strip()
ot = ot.replace('^\s*|\s*$', '')
otp_list.append(ot)
otp_num = len(otp_list) + 1
if (otp_num > 0):
os.remove(rsg_file)
try :
new_otp = otp_list[0]
except IndexError:
printlog('There is no otp left ,please input new OTP list')
sendworker(mail_addr)
sys.exit()
else:
out = open(rsg_file, 'w')
for line in rsg_in :
line = line.strip()
line = line.replace('^\s+|\s+$','')
if (re.match(egwname, line)):
temp_line = line
old_otp = re.split('\s+',temp_line)[5]
old_otp = old_otp.replace('^\s+|\s+$', '')
line = line.replace(old_otp, new_otp).replace('\\','')
printlog(line + "\n")
out.write(line + "\n")
out.close()
os.remove(otp_file)
time.sleep(1)
outotp = open(otp_file , 'w+')
i = 0
while (i < len(otp_list)):
outotp.write(otp_list[i] + "\n")
i += 1
outotp.close()
os.system("pkill -9 -f \"ssh\.\*-L " + str(nLocalport) + "\"")
os.system("sleep 10")
os.system("pkill -9 -f \"rtunnel\.\*-p " + str(nLocalport) + "\"")
os.system("nohup /opt/ericsson/itk/bin/rtunnel -d -q -g -p " + str(nLocalport) + "-rp auto " + rsg_target + " &")
os.system("sleep 10")
printlog("Kill the rtunnel process\n");
printlog("Tunnel is re-established again\n");
else:
sendworker(mail_addr)
except IOError:
print ("File is not accessible.")
else:
printlog("Tunnel OK")
As you see , after disable the line in Try... else... block, the code will be OK.
else:
ssh.expect(pexpect.EOF)
print (ssh.before.decode(),ssh.after().decode()) # if I disable this line, there will be no error.
flag = ssh.before.decode()
return flag
If you look carefully your traceback, you will find the problem:
Instead of:
print (ssh.before.decode(),ssh.after().decode())
you should write
print (ssh.before.decode(),ssh.after.decode())
after is a method which return string, not a function.
BTW, I think you should put decoding/encoding in your pexpect constructor.

How to remove \n at end of file name

When the following bit of code runs, most specifically the last 'else'condition, I get this error: OSError: [Errno 22] Invalid argument: 'My Name\n-Groups.txt'
What should I do so that '\n' isn't included in the file name as I would like it to just be 'My Name-Groups.txt'.
def add_child_to_group():
file = open("Children.txt", 'r') # open the Children.txt file
lineList = file.readlines()
lineList.sort()
file.close()
choice1 = choicebox('Choose a child to enter into a group.', 'Add child to a group. ', choices=lineList)
if choice1 is None:
print("You cancelled... returning to the main menu.")
main()
return
else:
file = open("Groups.txt", 'r')
lineList = [line.strip() for line in file]
choice2 = choicebox("Which group would you like to add the child to?", "Choose a group.",
choices=lineList)
file.close()
if choice2 is None:
print("You cancelled... returning to the main menu.")
main()
return
else:
if choice1 in open('%s.txt' % choice2).read():
child_already_in_group(choice1, choice2)
return
else:
file1 = open('%s.txt' % choice2, 'a')
file1.write(str(choice1))
print(str(choice1) + "was added to the " + str(choice2) + " group")
file1.close()
file2 = open('%s-Groups.txt' % choice1, 'a')
file2.write(str(choice2))
Something like this can do:
>>> st = 'My Name\n-Groups.txt'
>>> st.replace('\n','')
'My Name-Groups.txt'
>>>
So, in your code, you can make the following change:
file2 = open(('%s-Groups.txt' % choice1).replace('\n',''), 'a')

Something wrong with call function

I don't know where does it goes wrong. I can get the correct result if I just call out my valid_ISBN(isbn) function, but when I write the file, the result become all invalid. (maybe something wrong with function call, but I don't know how to fix it)
def main():
# Call and open the File
inFile = open("isbn.txt", "r")
for line in inFile:
line_strip = line.replace("-", "").replace(" ", "").rstrip("\n")
isbn = line_strip # the function call
# Output file
str = []
str.append(line)
outFile = open("isbnOut.txt", "a")
for i in str:
if valid_ISBN(isbn) == "valid":
outFile.write(i.strip() + " valid\n")
else:
outFile.write(i.strip() + " invalid\n")
inFile.close()
outFile.close()
def valid_ISBN(isbn):
if len(isbn) != 10 or (isbn[0:9].isdigit()) == False:
print("invalid")
else:
return partial_sums(isbn)
def partial_sums(s1):
lst1 =[]
sum1 = 0
for i in range(len(s1)):
if (i == (len(s1) -1)) and ((s1[i] == "x") or (s1[i] == "X")):
sum1 = sum1 + 10
else:
sum1 = sum1 + int(s1[i])
lst1.append(sum1)
#print(lst1)
sum_of_s1(lst1)
def sum_of_s1(s2):
lst2 = []
sum2 = 0
for i in s2:
sum2 += i
lst2.append(sum2)
#print(lst2)
checkISBN(lst2[-1])
def checkISBN(value):
if value % 11 == 0:
print("valid")
else:
print("invalid")
main()
2 Test case for isbn text file (no new line):
019-923-3241
818-851-703X
In your main function:
Every time you read a line in from your input file you initialize str and fill it with just one value. You open your output file, do your validity checks for your one value in str, and finally write the one value to the the output file.
The next time you read the file you do the same stuff... so str isn't needed at all
Also using str as a variable name is bad form. In your console write in help(str) and you will see why.
Now to deal with your actual complaint:
Your problem is the fact that there is no new line.
when you say for line in some_open_file_handler:... what python does is populate line with everything up to the next newline character or the end of the file.
If your input file has no new lines seperating isbns then the first value of line would be 019-923-3241 818-851-703X. Thus the line line_strip = line.replace("-", "").replace(" ", "").rstrip("\n") set linestrip to 0199233241818851703X
This should fix it:
'line.split() will yield ['019-923-3241','818-851-703X']
outFile = open("isbnOut.txt", "a")
for line in open("isbn.txt", "r"):
isbns = line.split() #this splits stuff up by whitespace.
for isbn in isbns:
isbn = isbn.replace("-", "").replace(" ", "").rstrip("\n")
if valid_ISBN(isbn) == "valid":
outFile.write(i.strip() + " valid\n")
else:
outFile.write(i.strip() + " invalid\n")

Resources