I am making one tool, and for this I want to save result of this tool in field that I've added. I want give name to that field on the basis of amenity selection (Here I've given data type of amenity as string. and added a list of values in amenity parameter like Education, Medical, Transportation, etc.). If I select "education" from amenities then my field name is like "Edu_IC". How can I do this? I've added my code snippet below
def setupVulnerability():
GP = ARC.create(9.3)
print(SYS.version)
InputFC = GP.GetParameterAsText(0) # Input Feature Class
print "InputFC:-'%s'" % (InputFC)
Fields = GP.GetParameterAsText(1)
print "Fields:-'%s'" % (Fields)
fieldList = Fields.split(";")
print "fieldList:-'%s'" % (fieldList)
amenity = GP.GetParameterAsText(2)
print "amen:-'%s'" % (amenity)
all_field_names = [f.name for f in arcpy.ListFields(InputFC)]
field_Name = None
try:
for field in fieldList:
field_Name = field[0:3]+ "_" + "IC"
if field_Name in all_field_names:
continue
else :
GP.AddField(InputFC , field_Name , "FLOAT")
field_Name = None
except:
raise ERROR.ScriptError()
if __name__ == '__main__':
setupVulnerability()
I believe the problem is that your "amenity" variable, which receives input from the user, is not referenced when the field is being added.
Something like this should work:
amenity = GP.GetParameterAsText(2)
if amenity == "Education":
field_name = amenity[:3] + "_IC"
GP.AddField(InputFC, field_Name, "FLOAT")
Related
I have gotten mostly through this assignment but I am stuck as to obtain the proper outputs.
This assignment wishes that if the inputs are a full name, that the outputs are "last name, first initial. last initial. If the input was Stacy Estel Graham, the expected output should be Graham, S.E.
"Many documents use a specific format for a person's name. Write a program whose input is:
firstName middleName lastName
and whose output is:
lastName, firstInitial.middleInitial."
full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
mod_name.join('.')
print(last_name)
print(mod_name)
I am completely lost on how to proceed.
You need to use '.'.join() to get the initials added.
To extract only the first char from the name, you can do mod_name[i][:1] where i is the index from 0 until last name - 1.
You can do something like this:
full_name = input('Enter your full name :')
mod_name = full_name.split(' ')
temp = '.'.join([mod_name[i][0] for i in range (0, len(mod_name) - 1)])
if temp == '':
print (mod_name[-1])
else:
print (mod_name[-1] + ', ' + temp + '.')
Here are some of the sample runs:
Enter your full name :Stacy Estel Sugar Graham
Graham, S.E.S.
Enter your full name :Stacy Estel Graham
Graham, S.E.
Enter your full name :Stacy Graham
Graham, S.
Enter your full name :Graham
Graham
Use:
def format_name(name):
names = name.split()
return f"{names[-1]}, {''.join([f'{i[0]}.' for i in names[:-1]])}"
Examples:
format_name('Stacy Estel Graham')
# > 'Graham, S.E.'
format_name('Randall McGrath')
# > 'McGrath, R.'
this code help you,but middle name is must for every person for creating your desire output
import re
s="Stacy Estel Graham"
words=s.split()
k=re.findall("[A-Z]",s)
p=words[-1]+","+k[0]+"."+k[1]
print(p)
Output:
Graham,S.E
Not with re :
full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
first_inital = mod_name[0][0]
if len(mod_name) >= 2:
middle_inital = mod_name[1][0]
print(f'{last_name}, {first_inital}.{middle_inital}')
else:
print(f'{last_name}, {first_inital}.')
You can use string indexing and f' string format.
Input:
Hello World Python
Output:
Python, H.W.
full_name = input(')
mod_name = full_name.split(' ')
temp = '.'.join([mod_name[i][0] for i in range (0, len(mod_name) - 1)])
if temp == '':
print (mod_name[-1])
else:
print (mod_name[-1] + ', ' + temp + '.')
I am trying to add some value and key in python dictionary using following script
print('phone book contacts')
contacts = input('how many contacts to add: ')
i = 0
for i in range(int(contacts)):
phone_book = {}
a = input('name: ')
b = input('number: ')
phone_book[a] = b
print(phone_book)
when i input 2 key & value like these:
adam : 08123
daniel : 0877
I expect the output will be like these:
{'adam':'08123', 'daniel':'0877'}
instead I get the following output:
{'daniel': '1234'}
any ideas how to show dictionary key & value similar with my expected output?
You can try something like this:
class my_dictionary(dict):
# __init__ function
def __init__(self):
self = dict()
# Function to add key:value
def add(self, key, value):
self[key] = value
# Main Function
dict_obj = my_dictionary()
# Taking input key = 1, value = test
dict_obj.key = input("Enter the key: ")
dict_obj.value = input("Enter the value: ")
dict_obj.add(dict_obj.key, dict_obj.value)
dict_obj.add(2, 'test2')
print(dict_obj)
Use update() method of dictionary class in python.
So if applied to your code
It would be
print('phone book contacts')
contacts = input('how many contacts to add: ')
i = 0
phone_book = {}
for i in range(int(contacts)):
a = input('name: ')
b = int(input('number: '))
phone_book.update({a : b})
print(phone_book)
Since number is integer you have to use curly braces.
And yes move phone_book = {} above the loop because it will be set to empty every time it loops.
I have a big chunk of json code. I assign the needed me values to more than +10 variables. Now I want to print all variable_name = value using print how I can accomplish this task
Expected output is followed
variable_name_1 = car
variable_name_2 = house
variable_name_3 = dog
Updated my code example
leagues = open("../forecast/endpoints/leagues.txt", "r")
leagues_json = json.load(leagues)
data_json = leagues_json["api"["leagues"]
for item in data_json:
league_id = item["league_id"]
league_name = item["name"]
coverage_standings = item["coverage"]["standings"]
coverage_fixtures_events =
item["coverage"]["fixtures"]["events"]
coverage_fixtures_lineups =
item["coverage"]["fixtures"]["lineups"]
coverage_fixtures_statistics =
item["coverage"]["fixtures"]["statistics"]
coverage_fixtures_players_statistics = item["coverage"]["fixtures"]["players_statistics"]
coverage_players = item["coverage"]["players"]
coverage_topScorers = item["coverage"]["topScorers"]
coverage_predictions = item["coverage"]["predictions"]
coverage_odds = item["coverage"]["odds"]
print("leagueName:" league_name,
"coverageStandings:" coverage_standings,
"coverage_fixtures_events:"
coverage_fixtures_events,
"coverage_fixtures_lineups:"
coverage_fixtures_lineups,
"coverage_fixtures_statistics:"
coverage_fixtures_statistics,
"covage_fixtes_player_statistics:"
covage_fixres_players_statistics,
"coverage_players:"
coverage_players,
"coverage_topScorers:"
coverage_topScorers,
"coverage_predictions:"
coverage_predictions,
"coverage_odds:"coverage_odds)
Since you have the JSON data loaded as Python objects, you should be able to use regular loops to deal with at least some of this.
It looks like you're adding underscores to indicate nesting levels in the JSON object, so that's what I'll do here:
leagues = open("../forecast/endpoints/leagues.txt", "r")
leagues_json = json.load(leagues)
data_json = leagues_json["api"]["leagues"]
def print_nested_dict(data, *, sep='.', context=''):
"""Print a dict, prefixing all values with their keys,
and joining nested keys with 'separator'.
"""
for key, value in data.items():
if context:
key = context + sep + key
if isinstance(value, dict):
print_nested_dict(value, sep=sep, context=key)
else:
print(key, ': ', value, sep='')
print_nested_dict(data_json, sep='_')
If there is other data in data_json that you do not want to print, the easiest solution might be to add a variable listing the names you want, then add a condition to the loop so it only prints those names.
def print_nested_dict(data, *, separator='.', context=None, only_print_keys=None):
...
for key, value in data.items():
if only_print_keys is not None and key not in only_print_keys:
continue # skip ignored elements
...
That should work fine unless there is a very large amount of data you're not printing.
If you really need to store the values in variables for some other reason, you could assign to global variables if you don't mind polluting the global namespace.
def print_nested_dict(...):
...
else:
name = separator.join(contet)
print(name, ': ', value, sep='')
globals()[name] = value
...
I wanted the user to input a particular product name (which is saved in a file) and accordingly I wanted to print out price of the product (saved in a different file), but not able to do so.
I have just started out programming, so it's new to me.
def find_in_file(f) :
myfile = open("file1.txt")
products = myfile.read()
products = products.splitlines()
if f in products:
return "Product is in list"
else:
return "Product is not in list"
def printing_in_file(p) :
myprice = open("file2.txt")
price = myprice.read()
price = price.splitlines()
return price
if code in sec_code.values():
product = input("Enter product name: ")
print(printing_in_file(p))
I expected the price to be the output, but I am getting name 'p' is not defined.
This answer below works, but it is not complete, because you did not provide samples of your input files.
The code that you provided does not have a 'p' variable, so I replace it with the variable product. I created bool values for the returns in the function find_product (which was named find_in_file). If the inputted product name is an exact match (this will create problems) then a bool value of True is return. Next the code will call the function find_product_price (which was named printing_in_file) for the product name. I had to create files containing product names and prices, because you did not provide sample files as part of your question.
This code works, but it has limitation, because I do not know the exact format of your inputs files or sec_code values. With additional information this code can be improved or something new might replace some of it with something better.
Good luck with this coding problem.
def find_product(product_name) :
inventory_file = open('tmpFile.txt', 'r', encoding='utf-8')
products = inventory_file.read()
products = products.splitlines()
if product_name in products:
return True
else:
return False
def find_product_price(product_name) :
product_prices = open('tmpFile01.txt', 'r', encoding='utf-8')
prices = product_prices.read()
price = prices.splitlines()
if product_name in price:
return price
product = input("Enter product name: ")
product_search = find_product(product)
if product_search == True:
print ('The product is available.')
print(find_product_price(product))
# outputs
['cisco router $350']
elif product_search == False:
print (f'{product} are not available for purchase.')
mine is homework question in response to the previous Question i posted on this site:
i redid the code to the following:
import re
people = ["Karen", "Peter", "Joan", "Joe", "Carmen", "Nancy", "Kevin"]
phonenumbers = ["201-222-2222", "201-555-1212", "201-967-1490", 201-333-3333",'201-725-3444", "201-555-1222", "201-444-4656"]
name = raw_input("Enter person's name:")
found = false
for i in range(0, len(people)):
value = people[i]
m = ("(" + name + ".*)",value)
if m:
found = True
print (people[i], phonenumber[i])
else:
print ("No matching name was found.")
My question is how do i tell the program to check if Karen's phone number is the 201-222-2222? And Yes this is a homework assignment. I changed the names and the phone numbers in my acutal program.
When i run this program and type any character all the names and phone number show up that's where i'm having difficutly...
EDITED: Question isn't clear to me.
The following code my help.
1.) First it ask for name then check if it exist in the people list.
2.) Then if it exist it saves it in variable called abc.
3.) After loop is finished it prints the abc which is the name you entered and that person phone number.
import re
people = ["Karen", "Peter", "Joan", "Joe", "Carmen", "Nancy", "Kevin"]
phonenumbers = ["201-222-2222", "201-555-1212", "201-967-1490", "201-333-3333","201-725-3444", "201-555-1222", "201-444-4656"]
name = input("Enter person's name:")
abc = "" # Will store the name and phone number
found = False
for i in range(0, len(people)):
if people[i].lower() == name.lower(): #checks if input name match + use method to lower all char
abc = people[i]+" Has the number "+phonenumbers[i]
value = people[i]
m = ("(" + name + ".*)",value)
if m:
found = True
print (people[i], phonenumbers[i]) # missing letter "s"
else:
print ("No matching name was found.")
print("\n"+abc)
Result