Python statement merge - python

I have a standard format letter(in txt format) and within it I want to replace some words(keywords) with the words I have created in a separate wordlist.
to visualise my letter is:
Dear [name],
I have b-day party on [date] at [venue]
please be there # [time]
Sincerely,
the following is the file that I would like to replace:
Mary
12.02.2022
Soho House
08.00pm
so Mary would be seen on the [name] and 12.02.2022 is seen on the [date] such as:
Dear Mary,
I have a b-day party on 12.02.2022 xxxx
Following code didnot work. Could you please support how to solve this issue?
import keyword
placeholder1="[name]"
placeholder2="[date]"
placeholder3="[venue]"
placeholder4="[time]"
with open("occurence.txt") as letter:
keyref=letter.readlines()
with open("sample_letter.txt") as target:
target_contents=target.read()
for name in keyref:
word1=target_contents.replace(placeholder1,name)
for date in keyref:
word2 = target_contents.replace(placeholder2, date)
print(word1)
print(word2)

You don't need to import keywords use variables instead. Write things and that. I don't think it will work that way. Please sort it out nicely. You can also make it so that it is an input but this is what I wrote:
name = 'name'
date = 'date'
venue = 'venue'
time = 'time'
print("Dear ",name + "\nI have b-day party on ",date + "at ",venue +
"please be there #",time + "\nSincerely,"

Related

Creating User Name from Name in Python

I have a spreadsheet with data. There I have a name like Roger Smith. I would like to have the user name rsmith.
Therefore, the first letter of the first name followed by the family name. How can I do this in Python?
def make_username(full_name: str) -> str:
first_names, last_name = full_name.lower().rsplit(maxsplit=1)
return first_names[0] + last_name
print(make_username("Roger M. Smith"))
Output: rsmith
The use of rsplit is to ensure that in case someone has more than one first name, the last name is still taken properly. I assume that last names will not have spaces in them.
Note however that depending on your use case, you may need to perform additional operations to ensure that you don't get duplicates.
By passing the 0 index to the full name we get the first letter of the name.
Using the split() function we can convert the full_name into list. Then passing -1 index we can get the family name.
Lower() will convert the name into lower case.
full_name = 'Roger Smith'
username = full_name[0] + full_name.split()[-1]
print(username.lower())
#output : rsmith
Here's an option in case you are also interested in generating usernames using last name followed by first letter of first name:
name = 'Roger R. Smith'
def user_name_generator(name,firstlast = True):
username = name.lower().rsplit()
if firstlast:
username = username[0][0] + username[-1]
else:
username = username[-1] + username[0][0]
return username
This outputs rsmith if the parameter firstlast is set to True and outputs smithr if firstlast is set to False
if I understand your question correctly, you want to iterate through all the names of an excel sheet in the format 'firstletternamesurname'. This can be done with pandas, but I don't know if that's exactly what you want. With pandas there will be a final dataframe and you can export it to excel again. Try this:
import pandas as pd
df = pd.read_excel('name.xlsx')
for i in df:
df1 = df['name'].iloc[0] + df['surname'].iloc[0]
df2 = df1.split()[0]
print(df2.lower())

Validate list of last names of Hotel Guests according to the corresponding first name in a text file in Python

I have a text file called listofhotelguests.txt where hotelguests are stored line by line with their first names separated by && as a delimiter. Can someone explain how I can have my Python program read it so it associates john with doe, ronald with macdonald, and george with washington?
My expected outcome I'm hoping for is if I prompt the user for their lastname to make sure their a valid guest on the list, the program will check it against what it has in the file for whatever the firstname they entered earlier was.
So if someone enters george as their first name, the program retrieves the line where it has george&&washington, prompts the user to enter their lastname and if it doesn't match what it has, either say it matches or doesn't. I can figure the rest out later myself.
Assuming there is nobody with the same names.
I know I have to split the lines with &&, and somehow store what's before && as something like name1 and whats after && as name2? Or could I do something where if the firstname and lastname are on the same line it returns name1 and password1?
Not sure on what to do. Python is one of my newer languages, and I'm the only CS student in my family and friend groups, so I couldn't ask anybody else for help. Got nowhere by myself.
Even just pointing me in the direction of what I need to study would help immensely.
Thanks
Here's what the text file looks like:
john&&doe
ronald&&macdonald
george&&washington
abraham&&lincoln
Here's some pseudocode:
listoffirstnames = []
listoflastnames= []
with open ("listofhotelguests.txt") as guestlist:
for line in guestlist
listoffirstnames.append()
listoflastnames.append()
while True:
firstname = input("Please enter your firstname")
if (firstname in listoffirstnames):
print("Hello" ,firstname)
break
else:
print("Sorry, you weren't in the list. Please try again")
while True:
print("Hello " + firstname + " please enter your last name.")
lastname = input("Enter lastname to verify guest status: ")
if (lastname in listoflastnames):
print("Welcome back!" + firstname + lastname)
break
else:
print("Sorry, the lastname was entered wrong")
Here's a solution:
first_names = []
last_names = []
with open("bruh.txt") as f:
for line in f:
name = line.strip().split("&&")
first_names.append(name[0])
last_names.append(name[1])
print(first_names)
print(last_names)
Basically, strip() removes any pesky unwanted spaces on either end, and the split() function allows you to split a string based on the parameter, here &&. So name ends up storing the first and last name as a list, and you can access them through subscripts.
That said, a long-term better solution would be to store both the first and last names together as a list, inside a bigger list of all names. For example,
names = [['john', 'doe'], ['firstname', 'lastname'], ...]
For that you can use this:
names = []
with open("bruh.txt") as f:
for line in f:
name = line.strip().split("&&")
names.append(name)
print(names)
Which outputs: [['john', 'doe'], ['ronald', 'macdonald'], ['george', 'washington'], ['abraham', 'lincoln']]
Admittedly, this does require more code to access all first and last names separately, but as I said, the convenience of having both parts of the name as part of a single list of names is a better long term approach.

Counting date occurrences in python?

I'm currently trying to count the number of times a date occurs within a chat log for example the file I'm reading from may look something like this:
*username* (mm/dd/yyyy hh:mm:ss): *message here*
However I need to split the date from the time as I currently treat them as one. Im currently struggling to solve my problem so any help is appreciated. Down below is some sample code that I'm currently using to try get the date count working. Im currently using a counter however I'm wondering if there are other ways to count dates.
filename = tkFileDialog.askopenfile(filetypes=(("Text files", "*.txt") ,))
mtxtr = filename.read()
date = []
number = []
occurences = Counter(date)
mtxtformat = mtxtr.split("\r\n")
print 'The Dates in the chat are as follows'
print "--------------------------------------------"
for mtxtf in mtxtformat:
participant = mtxtf.split("(")[0]
date = mtxtf.split("(")[-1]
message = date.split(")")[0]
date.append(date1.strip())
for item in date:
if item not in number:
number.append(item)
for item in number:
occurences = date.count(item)
print("Date Occurences " + " is: " + str(occurences))
Easiest way would be to use regex and take the count of the date pattern you have in the log file. It would be faster too.
If you know the date and time are going to be enclosed in parentheses at the start of the message (i.e. no parentheses (...): will be seen before the one containing the date and time):
*username* (mm/dd/yyyy hh:mm:ss): *message here*
Then you can extract based on the parens:
import re
...
parens = re.compile(r'\((.+)\)')
for mtxtf in mtxtformat:
match = parens.search(mtxtf)
date.append(match.group(1).split(' ')[0])
...
Note: If the message itself contains parens, this may match more than just the needed (mm/dd/yyyy hh:mm:ss). Doing match.group(1).split(' ')[0] would still give you the information you are looking for assuming there is no information enclosed in parens before your date-time information (for the current line).
Note2: Ideally enclose this in a try-except to continue on to the next line if the current line doesn't contain useful information.

Is it possible to separate multiple values pulled in from a SQLite3 Row using Python?

I have a database row that links, as an example, the name Mike to the description blonde, short, glasses. Current, if I were to run person.description, it prints out like this:
" ""blonde""", 'short', 'glasses',
Is it possible to separate these values and eliminate the extra '"'s? Here are a few things I've tried:
for i in person:
for j in i['description']:
print j
This returns each descriptive word character by character:
"
"
"
b
l
o
n
d
e
"
"
"
,
Next I tried:
for i in plugins:
print i['sets_kb_item']
This returned:
" ""blonde""", 'short', 'glasses',
I've also tried this, just trying to get lucky:
for i in person:
for j in i:
print j['description']
But this gave me a TypeError:
TypeError: 'int' object has no attribute '__getitem__'
Here is an example of a row in the sqlite database that I am querying:
Name: Description:
Mike 'blonde', "" """"short"""""", 'glasses',"
And here is the query I'm using:
cur = db.execute("select * from person where description like ?", (query,))
My end goal is to have output that prints something like:
Name: Mike
- blonde
- short
- glasses
Ultimately, I need to revisit just what the heck went on when I imported these values into my DB, but is there anything I can do until then?
Lets say you have a variable:
a = "\"\"blonde\"\""
Now when you print it, you'll see this
""blonde""
To remove the extra '"', I'd do this,
b=a.strip('\"')
print(b)
This would print:
blond
To separate on a ',' , you should do a split,
c=a.split(',')
Where c would become an array:
['blonde', 'short', 'glasses']
This gave you an array with your elements, now you can do any amount of processing you want.
So the total code would look somewhat like this considering a is your input string:
a=a.strip('\"').split(',')
for x in a:
print(a)
I hope this helps with your problem.

Python - changing the output when querying my CSV file

I have been tasked to create a program in Python which searches through a CSV file; a list of academic papers (Author, Year, Title, Journal - it's actually TSV).
With my current code, I can achieve correct output (as in the information is correct), but it is not formatted correctly.
What I'm getting is;
['Albers;Bergman', '1995', 'The audible Web', 'Proc. ACM CHI']
Where as what I need is this format;
Author/s. (Year). Title. Journal.
So the commas are changed for full stops (periods).
Also the ; between authors should be changed for an & sign if there are two authors, or there should be a comma followed by an & for three or more authors.
I.E
Glenn & Freg. (1995). Cool book title. Epic journal title.
or
Perry, Smith # Jones. (1998). Cooler book title. Boring journal name.
I'm not entirely sure how to do this. I have searched the python reference, google and here at Stackoverflow, but couldn't come across anything (that I understood at least). There is a LOT on here about completely removing punctuation, but that isn't what I'm after.
I first thought the replace function would work, but it gives me this error. (I'll leave the code in to show what I was attempting, but commented out)
str.replace(',', '.')
TypeError: replace() takes at least 2 arguments (1 given)
It wouldn't have totally solved my problem, but I figured it's something to move from. I'm assume str.replace() won't take punctuation?
Anyway, below is my code. Anybody have any other ideas?
import csv
def TitleSearch():
titleSearch = input("Please enter the Title (or part of the title). \n")
for row in everything:
title = row[2]
if title.find(titleSearch) != -1:
print (row)
def AuthorSearch():
authorSearch = input("Please type Author name (or part of the author name). \n")
for row in everything:
author = row[0]
if author.find(authorSearch) != -1:
#str.replace(',', '.')
print (row)
def JournalSearch():
journalSearch = input("Please type in a Journal (or part of the journal name). \n")
for row in everything:
journal = row[3]
if journal.find(journalSearch) != -1:
print (row)
def YearSearch():
yearSearch = input("Please type in the Year you wish to search. If you wish to search a decade, simply enter the first three numbers of the decade; i.e entering '199' will search for papers released in the 1990's.\n")
for row in everything:
year = row[1]
if year.find(yearSearch) != -1:
print (row)
data = csv.reader (open('List.txt', 'rt'), delimiter='\t')
everything = []
for row in data:
everything.append(row)
while True:
searchOption = input("Enter A to search by Author. \nEnter J to search by Journal name.\nEnter T to search by Title name.\nEnter Y to search by Year.\nOr enter any other letter to exit.\nIf there are no matches, or you made a mistake at any point, you will simply be prompted to search again. \n" )
if searchOption == 'A' or searchOption =='a':
AuthorSearch()
print('\n')
elif searchOption == 'J' or searchOption =='j':
JournalSearch()
print('\n')
elif searchOption == 'T' or searchOption =='t':
TitleSearch()
print('\n')
elif searchOption == 'Y' or searchOption =='y':
YearSearch()
print('\n')
else:
exit()
Thanks in advance to anybody who can help, it's really appreciated!
What you've got so far is a great start; you just need to process it a little further. Replace print(row) with PrettyPrintCitation(row), and add the function below.
Basically, it looks like you need to format the authors with a switch, which would best be implemented as a function. Then, you can handle the rest with just a nice format string. Suppose your reference rows look like the following:
references = [
['Albers', '1994', 'The audible Internet', 'Proc. ACM CHI'],
['Albers;Bergman', '1995', 'The audible Web', 'Proc. ACM CHI'],
['Glenn;Freg', '1995', 'Cool book title', 'Epic journal title'],
['Perry;Smith;Jones', '1998', 'Cooler book title', 'Boring journal name']
]
Then the following will give you what I believe you're looking for:
def PrettyPrintCitation(row) :
def adjustauthors(s):
authorlist = s[0].split(';')
if(len(authorlist)<2) :
s[0] = authorlist[0]
elif(len(authorlist)==2) :
s[0] = '{0} & {1}'.format(*authorlist)
else :
s[0] = ', '.join(authorlist[:-1]) + ', & ' + authorlist[-1]
return s
print('{0}. ({1}). {2}. {3}.'.format(*adjustauthors(row)))
applied to the citations above, this gives you
Albers. (1994). The audible Internet. Proc. ACM CHI.
Albers & Bergman. (1995). The audible Web. Proc. ACM CHI.
Glenn & Freg. (1995). Cool book title. Epic journal title.
Perry, Smith, & Jones. (1998). Cooler book title. Boring journal name.
(I'm assuming that "#" in your proposed output was a mistake...)
You need to work on your python syntax.
try something along these lines:
authorlist=row[0].split(';') # split the multiple authors on semicolon
authors=" & ".join(ahthorlist) # now join them together with ampersand
print"""%s. (%s) %s.""" % (authorlist,row[1],row[2]) # print with pretty brackets etc.

Categories