I am working on a script that sorts people's names. I had this working using the csv module, but as this is going to be tied to a larger pandas project, I thought I would convert it.
I need to split a single name field into fields for first, middle and last. The original field has the first name first. ex: Richard Wayne Van Dyke.
I split the names but want "Van Dyke" to be the last name.
Here is my code for the csv module that works:
with open('inputfil.csv') as inf:
docs = csv.reader(inf)
next(ccaddocs, None)
for i in docs:
#print i
fullname = i[1]#it's the second column in the input file
namelist =fullname.split(' ')
firstname = namelist[0]
middlename = namelist[1]
if len(namelist) == 2:
lastname = namelist[1]
middlename = ''
elif len(namelist) == 3:
lastname = namelist[2]
elif len(namelist) == 4:
lastname = namelist[2] + " " + namelist[3] #gets Van Dyke in lastname
print "First: " + firstname + " middle: " + middlename + " last: " + lastname
Here is my pandas-based code that I'm struggling with:
df = pd.DataFrame({'Name':['Richard Wayne Van Dyke','Gary Del Barco','Dave Allen Smith']})
df = df.fillna('')
df =df.astype(unicode)
splits = df['Name'].str.split(' ', expand=True)
df['firstName'] = splits[0]
if splits[2].notnull and splits[3].isnull:#this works for Bret Allen Cardwell
df['lastName'] = splits[2]
df['middleName'] = splits[1]
print "Case 1: First: " + df['firstName'] + " middle: " +df['middleName'] + " last: " + df['lastName']
elif splits[2].all() == 'Del':#trying to get last name of "Del Barco"
print 'del'
df['middleName'] = ''
df['lastName'] = splits[2] + " " + splits[3]
print "Case 2: First: " + df['firstName'] + " middle: " +df['middleName'] + " last: " + df['lastName']
elif splits[3].notnull: #trying to get last name of "Van Dyke"
df['middleName'] = splits[1]
df['lastName'] = splits[2] + " " + splits[3]
print "Case 3: First: " + df['firstName'] + " middle: " +df['middleName'] + " last: " + df['lastName']
There is something basic that I'm missing.
if len(name) >= 3: # (assume that user only has one middle name)
firstname = splits[0]
middlename = splits[1]
lastnames = splits[2:] ( catch all last names into a list )
Related
so I am writing a program to find specific lines in a dump from the uninstall registry, and then write those lines to a new text file. Here is the code.
fileName = "export.txt"
outputFileName = input("Enter the Output File Name")
inputFile = open(fileName, "r")
outputFile = open(outputFileName, "w")
displayName = ""
displayVersion = ""
publisher = ""
for line in inputFile:
if "DisplayName" in line:
lst = line.split("=")
displayName = lst[1][1:len(lst[1])-1]
if "DisplayVersion" in line:
lst = line.split("=")
displayVersion = lst[1][1:len(lst[1])-1]
if "Publisher" in line:
lst = line.split("=")
publisher = lst[1][1:len(lst[1])-1]
if displayName!= "" or displayVersion != "" or publisher != "":
outputFile.write(displayName + "\t" + displayVersion + "\t" +publisher + "\n")
displayName = ""
displayVersion = ""
publisher = ""
inputFile.close()
outputFile.close()
For some reason, the first three if statements are not being entered. Here is a snippet from the export.txt text file.
[HKEY_LOCAL_MACHINE\SoftWare\Microsoft\Windows\CurrentVersion\Uninstall\Matlab R2016b]
"DisplayName"="MATLAB R2016b"
"UninstallString"="C:\\Program Files\\MATLAB\\R2016b\\uninstall\\bin\\win64\\uninstall.exe C:\\Program Files\\MATLAB\\R2016b"
"DisplayIcon"="C:\\Program Files\\MATLAB\\R2016b\\bin\\win64\\matlab.ico"
"InstallLocation"="C:\\Program Files\\MATLAB\\R2016b"
"DisplayVersion"="9.1"
"URLInfoAbout"="www.mathworks.com"
"Publisher"="MathWorks"
"HelpLink"="www.mathworks.com/support"
"Comments"=" "
ê[HKEY_LOCAL_MACHINE\SoftWare\Microsoft\Windows\CurrentVersion\Uninstall\Matlab
R2016b]
“DisplayName””MATLAB R201 6b”
“UninstallString””C: \\Prograrn
Files\\MATLAB\\R2016b\\uninstall\\bin\\win64\\uninstall.exe C: \\Prograrn
Files\\frIATLAB\\R201 6b”
“Displaylcon””C:\\Prograrn Files\\MATLAB\\R2016b\\bin\\win64\\matlab. ico”
“InstallLocation””C: \\Prograrn Files\\MATLAB\\R201 6b”
“DisplayVersion””9. 1”
“URLlnfoAbout””www. mathworks. corn”
“Publisher”=”MathWorks”
“HelpLink””www. rnathworks. corn/support”
“Comments”” “
The logic of your last if statement is completely reversed. It should be or instead of and in order for your statement to work properly.
What about checking in a different way using find()?
if line.find("DisplayName") != -1:
do stuff.
I ran this fine, here's the code:
fileName = "export.txt"
outputFileName = input("Enter the Output File Name")
inputFile = open(fileName, "r")
outputFile = open(outputFileName, "w")
displayName = ""
displayVersion = ""
publisher = ""
for line in inputFile:
print line
if line.find("DisplayName") != -1:
lst = line.split("=")
displayName = lst[1][1:len(lst[1])-2]
if line.find("DisplayVersion") != -1:
print "here2"
lst = line.split("=")
displayVersion = lst[1][1:len(lst[1])-2]
if line.find("Publisher") != -1:
print "here3"
lst = line.split("=")
publisher = lst[1][1:len(lst[1])-2]
if displayName!= "" and displayVersion != "" and publisher != "":
print "Here4"
print displayName + "\t" + displayVersion + "\t" +publisher
outputFile.write(displayName + "\t" + displayVersion + "\t" +publisher)
displayName = ""
displayVersion = ""
publisher = ""
inputFile.close()
outputFile.close()
produces:
MATLAB R2016b 9.1 MathWorks
The output while running the script looks like this:
Enter the Output File Name"out.txt"
[HKEY_LOCAL_MACHINE\SoftWare\Microsoft\Windows\CurrentVersion\Uninstall\Matlab R2016b]
"DisplayName"="MATLAB R2016b"
"UninstallString"="C:\Program Files\MATLAB\R2016b\uninstall\bin\win64\uninstall.exe C:\Program Files\MATLAB\R2016b"
"DisplayIcon"="C:\Program Files\MATLAB\R2016b\bin\win64\matlab.ico"
"InstallLocation"="C:\Program Files\MATLAB\R2016b"
"DisplayVersion"="9.1"
here2
"URLInfoAbout"="www.mathworks.com"
"Publisher"="MathWorks"
here3
Here4
MATLAB R2016b 9.1 MathWorks
"HelpLink"="www.mathworks.com/support"
"Comments"=" "
me: I am very new to coding.
What i'm trying to do: Allow the user to change a txt files data. E.g. The name of a person, the email of a person, etc.
Problem: Code accepts my inputs however, it does not change the txt file.
Code i've made already.
click here for code
L = open("players.txt","r+")
edit_name = raw_input ("Enter the name of the person you wish to edit: ")
for line in L:
s = line.strip()
strings = s.split(",")
if edit_name == strings[0]:
print strings[:8]
print " \t 1 - Forename \n"
print " \t 2 - Surname \n"
print " \t 3 - Email Address \n"
print " \t 4 - Phone Number \n"
print " \t 5 - Division \n"
print " \t 6 - Points in the new division\n"
print " \t 7 - Old division\n"
print " \t 8 - Old points\n"
option = raw_input("Enter the number of what you would like to edit: ")
if option == "1":
updated_forename = raw_input ("New forename: ")
strings[0] = updated_forename
elif option == "2":
updated_surname = raw_input ("New surname: ")
strings[1] = updated_surname
elif option == "3":
updated_email = raw_input("New email: ")
strings[2] = updated_email
elif option == "4":
updated_phone_number = raw_input("New phonenumber: ")
strings[3] = updated_phone_number
elif option == "5":
updated_division = raw_input("New division: ")
strings[4] = updated_division
elif option == "6":
updated_points_new_div = raw_input("New points in division: ")
strings[5] = updated_points_new_div
elif option == "7":
updated_olddivision = raw_input("Old divison: ")
strings[6] = updated_olddivision
elif option == "8":
updated_oldpoints = raw_input("Old Points: ")
strings[7] = updated_oldpoints
print "Updated information"
print strings[:8]
L.close() #Closes the file to free us usage space.
Text file i'm wanting to edit.
click here for text file
Im guessing I need to basically save over the existing text file with the new data that has been entered. The question is how?
Any help would be appreciated.
p.s. First time posting so i cannot post pictures as i don't have 10 reputation. My apologies.
You are never actully writing to the file:
https://docs.python.org/2/tutorial/inputoutput.html
Change "L.open" to write mode "w", use "L.write()" to write new data, this means you need to rewrite the data you don't want to change and construct and write new data where you wanted it to be modified.
Pseudo-code:
Open file
for line in file
if(line.name == selectedname):
write_row_edited(something)
else:
write_line_unedited()
close file
I took the time to insert the missing peudo-code
#we need to load file into memory, so we can edit it (rewrite it modified)
file = open("players.txt","r")
data = file.read()
file.close()
datalines = data.split("\n")
#now we have the file "line-by-line" in memory so we can edit it
edit_name = raw_input ("Enter the name of the person you wish to edit: ")
file = open("players.txt","w")
for line in datalines:
s = line.strip()
strings = s.split(",")
if edit_name == strings[0]:
print strings[:8]
print " \t 1 - Forename \n"
print " \t 2 - Surname \n"
print " \t 3 - Email Address \n"
print " \t 4 - Phone Number \n"
print " \t 5 - Division \n"
print " \t 6 - Points in the new division\n"
print " \t 7 - Old division\n"
print " \t 8 - Old points\n"
option = raw_input("Enter the number of what you would like to edit: ")
if option == "1":
updated_forename = raw_input ("New forename: ")
strings[0] = updated_forename
elif option == "2":
updated_surname = raw_input ("New surname: ")
strings[1] = updated_surname
elif option == "3":
updated_email = raw_input("New email: ")
strings[2] = updated_email
elif option == "4":
updated_phone_number = raw_input("New phonenumber: ")
strings[3] = updated_phone_number
elif option == "5":
updated_division = raw_input("New division: ")
strings[4] = updated_division
elif option == "6":
updated_points_new_div = raw_input("New points in division: ")
strings[5] = updated_points_new_div
elif option == "7":
updated_olddivision = raw_input("Old divison: ")
strings[6] = updated_olddivision
elif option == "8":
updated_oldpoints = raw_input("Old Points: ")
strings[7] = updated_oldpoints
print "Updated information"
print strings[:8]
#merge string so we can write it back
newline = ",".join(strings)
file.write(newline+"\n")
else:
file.write(line+"\n")
file.close()
I am using a for loop for getting data from the user in command prompt using python 2.7. Then storing the data in a text file in certain format. I am looking for a method to get the data from the user and store it in a list and use it where required.
for Input_Number in range(Number_Of_Inputs):
Input_Number = Input_Number+1
GUI_Parameter = str(raw_input("Please enter input parameter " + str(Input_Number) + " :"))
GUI_Parameter_Name = str(raw_input("Enter the GUI name for the parameter " + str(Input_Number) + " :"))
Store_GUI_Parameter(Opened_File, GUI_Parameter, GUI_Parameter_Name)
I would like to use this data to store it in a specific location in a text file according to required syntax. The above code stores the data in the text file. But the problem is it doesn't store it at the required place.
def Store_GUI_Parameter(Opened_File, GUI_Parameter, GUI_Parameter_Name):
GUI_Description = "| " + '"'+ GUI_Parameter_Name + '"' + " |$" + GUI_Parameter.title() + " |"
Write_Data(Opened_File, GUI_Description)
print "GUI parameters written to NDF file"
return
The data storage is done using the above function...
I tried this, but unfortunately this also is not working
GUI_Parameter= []
GUI_Parameter_Name = []
for Input_Number in range(Number_Of_Inputs):
Input_Number = Input_Number+1
GUI_Parameter[Input_Number] = str(raw_input("Please enter input parameter " + str(Input_Number) + " :"))
GUI_Parameter_Name[Input_Number] = str(raw_input("Enter the GUI name for the parameter " + str(Input_Number) + " :"))
Using it outside the loop in the same function...
GUI_Description(Opened_File, GUI_Parameter_Name[Input_Number], GUI_Parameter[Input_Number])
The function implementation:
def GUI_Description(Opened_File, GUI_Parameter_Name[Input_Number], GUI_Parameter[Input_Number]):
Iteration = 0
while Iteration < Input_Number:
Iteration += 1
GUI_Description = "| " + '"'+ GUI_Parameter_Name[Input_Number] + '"' + " |$" + GUI_Parameter[Input_Number].title() + " |"
Write_Data(Opened_File, GUI_Description)
print "GUI parameters written to NDF file"
return
But it shows syntax error at the def GUI_Description
C:\Users\padmanab\Desktop>python CtoN.py File "CtoN.py", line 173
def GUI_Description(Opened_File, GUI_Parameter_Name[Input_Number], GUI_Parameter[Input_Number]):
^ SyntaxError: invalid syntax
The syntax error in the function GUI_Description is caused by your input arguments. 'GUI_Parameter_Name[Input_Number]' is not a valid input argument. Since your function requires both 'GUI_Parameter_Name' and 'Input_Number' they should be separate input arguments. The code snippet below would solve this syntax error:
def GUI_Description(Opened_File, Input_Number, GUI_Parameter_Name, GUI_Parameter):
...
The code below will give an 'index out of range' error since the lists 'GUI_Parameter' and 'GUI_Parameter_Name' have zero length.
GUI_Parameter= []
GUI_Parameter_Name = []
Number_Of_Inputs = 1
for Input_Number in range(Number_Of_Inputs):
Input_Number = Input_Number+1
GUI_Parameter[Input_Number] = str(raw_input("Please enter input parameter " + str(Input_Number) + " :"))
GUI_Parameter_Name[Input_Number] = str(raw_input("Enter the GUI name for the parameter " + str(Input_Number) + " :"))
If you want to add items to the arrays you should append them:
GUI_Parameter.append(raw_input())
I am trying to make my own log that makes a string of changed data between object (my old object and my new object) However i keep getting back empty string,
My code:
def log_fields(old_obj, new_obj):
fields = new_obj.__class__._meta.fields
changed_fields = ""
old_data = ""
new_data = ""
# get all changed data
for field in fields:
old_field_data = old_obj.__getattribute__(field.name)
new_field_data = new_obj.__getattribute__(field.name)
if old_field_data != new_field_data:
count =+ 1
# convert changed data to strings
# number + space + data + 5 spaces for next string
changed_fields.join(str(count)).join(" ").join(str(field)).join(" ")
old_data.join(str(count)).join(" ").join(str(old_field_data)).join(" ")
new_data.join(str(count)).join(" ").join(str(new_field_data)).join(" ")
print changed_fields
print old_data
print new_data
I got a feeling something with the string .join combination something is going wrong, cause trying this manually in shell seems to work up to the comparison. Not sure tho hos i should change the string
changed_fields = changed_fields + str(count) + "." + str(field.name) + " "
old_data = old_data + str(count) + "." + str(old_field_data) + " "
new_data = new_data + str(count) + "." + str(new_field_data) + " "
Seems to do the job, so for now, ill keep it at this
I've been working on a small contact importer, and now I'm trying to implement a block that automatically selects the output file format based on the number of contacts to be imported.
However, every time it results in the error:
KeyError: 'q'
I can't figure out for the life of me why this is happening, and I would love any help offered.
My idea of scalability is that the dictionary personDict would be of the format personDict = {nameid:[name,email]}, but nothing works.
Any help is good help,
Thanks
def autoFormat():
while True:
name = input("Enter the person's name \n")
if name == "q":
break
email = input("Enter the person's email \n")
personDict[name] = [name, email]
if len(personDict) <= 10:
keyValue = personDict[name]
for keyValue in personDict:
for key, value in personDict.iteritems():
combined = "BEGIN:VCARD\nVERSION:4.0\n" + "FN:" + name + "\n" + "EMAIL:" + email + "\n" + "END:VCARD"
fileName = name + ".vcl"
people = open(fileName, 'a')
people.write(combined)
people.close()
print("Created file for " + name)
autoFormat()
The main problem is that when the user types "q" your code leaves the while loop
with name keeping "q" as value. So you should remove this useless line:
keyValue = person_dict[name]
Since there is no element with key "q" in your dictionary.
Also in the export part you write in file values different from those you loop with.
Your code becomes:
if len(personDict) <= 10:
for name, email in personDict.values():
combined = "BEGIN:VCARD\nVERSION:4.0\n" + "FN:" + name + "\n" + "EMAIL:" + email + "\n" + "END:VCARD"
fileName = name + ".vcl"
people = open(fileName, 'a')
people.write(combined)
people.close()
print("Created file for " + name)