can not remove comma from unicode string in Python - python

I would like to remove a comma from a string in Python. This is the code that I am using:
next_column = unicode(my_value)
next_column.replace(",", " ")
next_column.translate(dict([[ord(char), u''] for char in u',']))
next_column.translate(dict([[ord(char), None] for char in u',']))
if my_key == "practice_name":
nc = str(next_column)
nc.replace(",", " ")
nc.replace(',', " ")
pprint(nc)
The pprint shows:
'Phoenix Electronics, LLC'
The comma is still there.
"my_value" comes from a Postgres database, an old legacy app where the company failed to check the encoding of what was going into the database.
I don't know if this is a code issue or an encoding issue. Does anyone have any suggestions?

Try on the same line like,
>>>>import string
>>>>transtab = string.maketrans(",", " ")
>>>>unicodestring = r'Phoenix Electronics, LLC'
>>>>unicodestring.translate(transtab)
'Phoenix Electronics LLC'

Related

Python script to get username and password from text?

I have a script for creating accounts that outputs the following:
creating user in XYZ: username: testing firstName: Bob lastName:Test email:auto999#nowhere.com password:gWY6*Pja&4
So, I need to create a python script that will store the username and password in a csv file.
I tried splitting this string by spaces and colons then indexing it, but this isn't working quite properly and could fail if the message is different. Does anyone have any idea how to do this?
Regex is almost always the answer to this type of issue:
import re
text = 'creating user in XYZ: username: testing firstName: Bob lastName:Test email:auto999#nowhere.com password:gWY6*Pja&4'
pattern = '.*username:\s*(\S+)\s*firstName:\s*(\S+)\s*lastName:\s*(\S+)\s*email:\s*(\S+)\s*password:\s*(\S+)'
values = re.findall(pattern, text)
print(values)
Output:
[('testing', 'Bob', 'Test', 'auto999#nowhere.com', 'gWY6*Pja&4')]
Regexr Pattern Explanation
I don't see the need for Regex here, a simple but robust parsing is enough:
def get_data(account: str, attribute: str) -> str:
data = ' '.join(account.split()).strip()
for k, v in {' :': ':', ' : ': ':', ': ': ':'}.items():
data = data.replace(k, v)
index1 = data.find(attribute)
index2 = data.find(' ', index1)
return data[index1 + len(attribute + ':'): len(account) if index2 == -1 else index2]
example of use:
acc = "username: testing firstName: Bob lastName:Test email:auto999#nowhere.com password:gWY6*Pja&4"
print(get_data(acc, 'username'))
print(get_data(acc, 'password'))
output:
testing
gWY6*Pja&4
As the generator is yours, you can control how the accounts are created and I personally think that Regex is not easy to maintain.
This approach works even adding extra spaces or changing the order of the attributes, e.g.:
acc = " username: testing firstName: Bob lastName :Test email:auto999#nowhere.com password : gWY6*Pja&4 "
acc = "firstName: Bob username: testing email:auto999#nowhere.com password:gWY6*Pja&4 lastName:Test "

Python placeholders in read text

I am fairly new to Python, teaching it to myself by watching tutorials and doing the trial and error kind of thing, and I ran into a task, which I am not able to solve right now:
I am reading from a file with following code:
def read_file(file):
try:
with open(file) as f:
content = f.read()
return content
except FileNotFoundError:
print("\nThis file does not exist!")
exit()
The file(.txt) I am reading contains a text with multiple placeholders:
Hello {name}, you are on {street_name}!
Now I want to replace the placeholders {name} and {street_name} with their corresponding variables.
I know how f-strings work. Can this somehow be applied to this problem too, or do I have to parse the text to find the placeholders and somehow find out the fitting variable that way?
Each text I read, contains different placeholders. So I have to find out, which placeholder it is and replace it with the according string.
Not sure if that is what you are looking for:
string = "Hello {name}, you are on {street_name}!"
string = string.format(name="Joe", street_name="Main Street")
print(string)
or
string = "Hello {name}, you are on {street_name}!"
name = "Joe"
street_name = "Main Street"
string = string.format(name=name, street_name=street_name)
print(string)
gives you
Hello Joe, you are on Main Street!
See here.
If you actually don't know what placeholders are in the text then you could do something like:
import re
string = "Hello {name}, you are on {street_name}!"
name = "Joe"
street_name = "Main Street"
placeholders = set(re.findall(r"{(\w+)}", string))
string = string.format_map({
placeholder: globals().get(placeholder, "UNKOWN")
for placeholder in placeholders
})
If you know that all placeholders are present as variables, then you could simply do:
string = "Hello {name}, you are on {street_name}!"
name = "Joe"
street_name = "Main Street"
string = string.format_map(globals())

Getting input from user and writing it to a text file

f=open("test.txt","w")
f.write("PERSONALINFO"+"\n")
f.write("\n")
f.close()
f=open("test.txt","a")
f.write("Customer 1 Info:""\n")
print()
print("Customer 1 input:")
user1_title=input("Enter Mr, Mrs, Miss, Ms:")
user1_name=input("Enter fullname:")
user1_town=input("Enter town and country you live in:")
user1_age=input("Enter birth MM/DD/YY with numbers:""\n")
print()
print("Name:",user1_title + "", user1_name,"\n""Hometown:",user1_town,"\n" "Age:", user1_age, file=f)
print("1.Student")
print("2.Not working")
User1_working_status=input("Enter working status:")
if user1_name=="1":
print("student")
elif user1_name=="2":
print("Not working")
input("Please explain why:")
I can't get my elif statement "Explain why" to print to my text file. Can anyone help me? I've tried everything but nothing works so I'm stuck.
From what I understand, you want to create and append all the information to a text file. For the Explain why part, you should store the information to a variable and then write to file. If you use the with context manager for file I/O, you would not have to close the file explicitly.
user1_title=input("Enter Mr, Mrs, Miss, Ms: ")
user1_name=input("Enter fullname: ")
user1_town=input("Enter town and country you live in: ")
user1_age=input("Enter birth MM/DD/YY with numbers:""\n")
print("1.Student")
print("2.Not working")
User1_working_status=input("Enter working status: ")
with open("test.txt", 'a+') as f:
if User1_working_status=="1":
f.write("{}\n{}\n{}\n{}\n".format("Name: " + user1_title + " " + user1_name, "Town: " + user1_town, "Age: " + user1_age, "Working status: student"))
elif User1_working_status=="2":
explain = input("Please explain why: ")
f.write("{}\n{}\n{}\n{}\n{}\n".format("Name: " + user1_title + " " + user1_name, "Town: " + user1_town, "Age: " + user1_age, "Working status: Not Working", "Reason: " + explain))
print("Information written to test.txt")
Hope this helps.
To write in your text file, you should use f.write instead of printing (which shows on the console). And as stated in the comments, remember to close the file when the program finished.
Also the working status is set in User1_working_status variable, and your if statement condition reads user1_name.

Using regular expressions to match a word in Python

I am using PRAW to make a reddit bot that takes the comment author of someone who says "alot" and stores their username into a list. I am having troubles with the regular expression and how to get the string to work. Here is my code.
#importing praw for reddit api and time to make intervals
import praw
import time
import re
username = "LewisTheRobot"
password =
r = praw.Reddit(user_agent = "Counts people who say alot")
word_to_match = ['\balot\b']
storage = []
r.login(username, password)
def run_bot():
subreddit = r.get_subreddit("test")
print("Grabbing subreddit")
comments = subreddit.get_comments(limit=200)
print("Grabbing comments")
for comment in comments:
comment_text = comment.body.lower()
isMatch = any(string in comment_text for string in word_to_match)
if comment.id not in storage and isMatch:
print("Match found! Storing username: " + str(comment.author) + " into list.")
storage.append(comment.author)
print("There are currently: " + str(len(storage)) + " people who use 'alot' instead of ' a lot'.")
while True:
run_bot()
time.sleep(5)
so the regular expression I am using looks for the word alot instead of alot as part of a string. Example zealot. Whenever I run this, it will not find a comment that I have made. Any suggestions?
You're checking with string operations, not RE ones, in
isMatch = any(string in comment_text for string in word_to_match)
The first in here checks for a substring -- nothing to do with REs.
Change this to
isMatch = any(re.search(string, comment_text) for string in word_to_match)
Moreover, you have an error in your initialization:
word_to_match = ['\balot\b']
'\b' is the character with code 0x08 (backspace). Always use raw string syntax for RE patterns, to avoid such traps:
word_to_match = [r'\balot\b']
Now you'll have a couple of characters, backslash then b, which RE will interpret to mean "word boundary".
There may be other bugs but I try not to look for more than two bugs per question...:-)

Python scp copy file with spaces in filename

I'm trying to copy files in local network with scp.
It's working well with filenames without spaces, but it crash with.
I've tried to replace " " with "\ " as this exemple, but it don't work.
Here is my code:
def connection(locals):
a = (int(re.search(br'(\d+)%$', locals['child'].after).group(1)))
print a
perc = (Decimal(a)/100)
print (type(perc)), perc
while gtk.events_pending():
gtk.main_iteration()
FileCopy.pbar.set_text("Copy of the file in the Pi... " + str(a) + "%")
while gtk.events_pending():
gtk.main_iteration()
FileCopy.pbar.set_fraction(perc)
file_pc = "/home/guillaume/folder/a very large name of file with space .smthg"
file_pi = "pi#192.168.X.X:/home/pi/folder/a very large name of file with space .smthg"
if " " in file_pc:
file_pc = fichier_pc.replace(" ", '\\\ ') # tried '\\ ' or '\ '
file_pi = fichier_pi.replace(" ", '\\\ ') # but no way
else:
pass
command = "scp %s %s" % tuple(map(pipes.quote, [file_pc, file_pi]))
pexpect.run(command, events={r'\d+%': connection}) # this command is using to get the %
How can I fix this problem ?
Thanks
Use subprocess module and/or shlex.split():
import subprocess
subprocess.call(['scp', file_pc, file_pi])
and you don't need to worry about escaping or quoting anything
You may keep local file file_pc as is (pipes.quote will escape the spaces). The remote file should be changed:
import pipes
file_pi = 'pi#192.168.X.X:/home/pi/folder/file with space.smth'
host, colon, path = file_pi.partition(':')
assert colon
file_pi = host + colon + pipes.quote(path)
i.e., user#host:/path/with space should be changed to user#host:'/path/with space'
You might want to look into fabric, a Python library that streamlines the use of SSH.
from fabric.state import env
from fabric.operations import get
env.user = 'username'
env.key_filename = '/path/to/ssh-key'
get('/remote_path/*', 'local_path/')

Categories

Resources