string python function to summarize data - code problem - python

I made the string function in pythonbelow to summarize a block of text. I'm not getting any final answer when I run the function. Can someone help figure out what I did wrong? Thanks.
def summary(data):
category = data.get("category", "")
article_date = data.get("date", "")
headline = data.get("headline", "")
return summary(data)
pass

You are recursively calling the summary function. Assuming that the code provided is the entire function, if you want to get any output, you'd need to use something like this rather than calling the function again. You would also have to print the return value of the function
def summary(data):
category = data.get("category", "")
article_date = data.get("date", "")
headline = data.get("headline", "")
return f"Category: {category}\nArticle Date: {article_date}\nHeadline: {headline}\n"
pass

Related

creating a class with two string fields that concatenate in a method, and a method to prints the result

this has to be more simple than it seems.
class stringjoiner:
stri_one = "I am "
stri_two = "really struggling with this"
def joiner(str, str):
self.stri_one = stri_one
self.stri_two = stri_two
result = join(stri_one + stri_two)
def printer():
print(result)
stringjoiner.printer()
I'm such a noob, i can't even get stack to display my code properly. this is my first post here.
so i can't access the strings directly to concatenate them.
what am I doing wrong?
edit:
my code now reads:
"""
class stringJoiner:
def __init__(self, stri_one:str, stri_two:str):
stri_one = "I am "
stri_two = "really struggling with this"
self.stri_one = stri_one
self.stri_two = stri_two
result = join(stri_one + stri_two)
return result
def printer(self):
print(result)
"""
i get that in the second method, result has the red squigglies because its a variable that is local to the previous method... no? so how do i make this thing print two concatenated strings without directly accessing the strings like join("this is a" + " string") ?
if you want to join two defined strings then just simpley
def joiner(stri_one,stri_two):
stri_three = stri_one + stri_two
return stri_three
if you want have words of a sentence in a list then you can use
text = ["there", "is" ,"a" ,"programmer"]
print(" ".join(text))
this is going to join the words in the list by putting a space between them.

Python Update random field choice function from OrderedDict Class

I'm trying to do a script that choose a string and update a current field, but for some reason the code doesn't update the last value when calling my changerandom function in the Greeting class.
...[snip]...
class Greeting(Packet):
fields = OrderedDict([
("Morning", "Hi"),
("Afternoon", "Good Afternoon!"),
("Evening", "Good Evening!"),
])
def change(self):
self.fields["Morning"] = "Good morning!"
def changerandom(self, n = 1):
function=[
{self.fields["Morning"]: "Hello!"},
{self.fields["Morning"]: "Bonjorno!"},
{self.fields["Morning"]: "Hola!"},
]
result = {}
for i in range(n):
result.update(choice(function))
print "Updated string:",result
return result
text = Greeting()
print text
text.change()
print text
text.changerandom()
print text
My code return the following:
Hi
Good morning!
Updated string: {'Good morning!': 'Hola!'}
Good morning!
While it should have returned:
Hi
Good morning!
Hola!
I'm not sure what i'm missing here, I don't see why I cannot update the last field.
Any help would be greatly appreciated!
The problem is that you're returning a result, without assigning it anywhere.
You also use the value of fields, rather than the key. So, your code should be something like
def changerandom(self, n = 1):
function=[
{"Morning": "Hello!"},
{"Morning": "Bonjorno!"},
{"Morning": "Hola!"},
]
for i in range(n):
result = choice(function)
self.fields.update(result)
print "Updated string:",result
return result
Note that we're using self.fields.update, and we're no longer returning anything.
Generally, it's good practice for your functions and methods to return something, or change something, but never both.

Quality Centre, TestSetFactory [PYTHON]

I have a problem with dumping testsets list from HP QC. I'm using TestSetFactory object and simple SQL query and I receive > object (I'd love to receive dictionary filled base dump. What is wrong with this code? If you have a questions about implementation some function, write.
def create(self):
self._report_connector.connect()
self.qc_test_set_factory = self._report_connector._get_factory(self._path)
test_sets = self.qc_test_set_factory.NewList("SELECT * FROM CYCLE ")
if test_sets == None:
print " no results"
for test in test_sets:
pprint.pprint(test) #<---- it print me <COMOBject <unknow>>
print len(test_sets) #<---- it print me 1
Not certain about the accuracy of the rest of the code, but you do not pass a SQL query to the TestSetFactory.NewList method. If you want everything, pass an empty string.
test_sets = self.qc_test_set_factory.NewList("")

Class returns empty list

I am trying to write a function which cleans up URLs (strips them of anything like "www.", "http://" etc.) to create a list that I can sort alphabetically.
I have tried to do this by creating a class including a method to detect the term I would like to remove from the URL-string, and remove it. The bit where I am struggling is that I want to add the modified URLs to a new list called new_strings, and then use that new list when I call the method for a second time on a different term, so that step by step I can remove all unwanted elements from the URL-string.
For some reason my current code returns an empty list, and I am also struggling to understand whether new_strings should be passed to __init__ or not? I guess I am a bit confused with global vs. local variables, and some help and explanation would be greatly appreciated. :)
Thanks! Code below.
class URL_Cleaner(object):
def __init__(self, old_strings, new_strings, term):
self.old_strings = old_strings
self.new_strings = new_strings
self.term = term
new_strings = []
def delete_term(self, new_strings):
for self.string in self.old_strings:
if self.term in string:
new_string = string.replace(term, "")
self.new_strings.append(new_string)
else:
self.new_strings.append(string)
return self.new_strings
print "\n" .join(new_strings) #for checking; will be removed later
strings = ["www.google.com", "http://www.google.com", "https://www.google.com"]
new_strings = []
www = URL_Cleaner(strings, new_strings, "www.")
Why are we making a class to do this?
for string in strings:
string.replace("www.","")
Isn't that what you're trying to accomplish?
Regardless the problem is in your class definition. Pay attention to scopes:
class URL_Cleaner(object):
def __init__(self, old_strings, new_strings, term):
"""These are all instance objects"""
self.old_strings = old_strings
self.new_strings = new_strings
self.term = term
new_strings = [] # this is a class object
def delete_term(self, new_strings):
"""You never actually call this function! It never does anything!"""
for self.string in self.old_strings:
if self.term in string:
new_string = string.replace(term, "")
self.new_strings.append(new_string)
else:
self.new_strings.append(string)
return self.new_strings
print "\n" .join(new_strings) #for checking; will be removed later
# this is referring the class object, and will be evaluated when
# the class is defined, NOT when the object is created!
I've commented your code the necessary reasons.... To fix:
class URL_Cleaner(object):
def __init__(self, old_strings):
"""Cleans URL of 'http://www.'"""
self.old_strings = old_strings
cleaned_strings = self.clean_strings()
def clean_strings(self):
"""Clean the strings"""
accumulator = []
for string in self.old_strings:
string = string.replace("http://", "").replace("www.", "")
# this might be better as string = re.sub("http://(?:www.)?", "", string)
# but I'm not going to introduce re yet.
accumulator.append(string)
return accumulator
# this whole function is just:
## return [re.sub("http://(?:www.)?", "", string, flags=re.I) for string in self.old_strings]
# but that's not as readable imo.
You just need to define new_strings as
self.new_strings = []
and remove new_strings argument from the constructor.
The 'new_strings' and 'self.new_strings' are two different lists.

Can't get python to read/display my variable

I have been working on this one program for hours now and I am still having no luck. I am trying to create a "search engine" where you can look products with a SKU number.
class SKU:
def __init__(self, name, product):
self.name = name
self.product = product
def displaySKU(self):
print "Sku Number : ", self.name, ", Product: ", self.product
sku90100 = SKU("90100", "10310, 00310")
sku90101 = SKU("90101", "10024, 00024")
sku90102 = SKU("90102", "10023")
sku90103 = SKU("90103", "10025")
sku90104 = SKU("90104", "10410")
search = input("Please type SKU Number")
if search in range(90100, 90106):
"sku",search.displaySKU
My problem is that I can't seem to get display the SKU information; I have tried removing, changing, and adding characters to the variables without success. I may have missed something thou, but all I now is that nothing that I try works. Please help me figure this out, and thank you for taking the time to read my question.
Instead of storing each product as its own variable, use a dict:
skus = {}
skus[90100] = SKU("90100", "10310, 00310")
skus[90101] = SKU("90101", "10024, 00024")
skus[90102] = SKU("90102", "10023")
skus[90103] = SKU("90103", "10025")
skus[90104] = SKU("90104", "10410")
Then you can check membership using in, and call the .displaySKU() method to print:
if search in skus:
skus[search].displaySKU()
Lastly, for Python 2, it's preferred to use raw_input instead of input. raw_input gives you a string though, so you want to convert that to an int to match your skus keys:
search = int(raw_input("Please type SKU Number"))

Categories