Combining Several Character Objects into a Single Object - html

I am trying to scrape text from a news article - I am doing this as follows:
library(rvest)
url <- "https://www.bbc.com/future/article/20220823-how-auckland-worlds-most-spongy-city-tackles-floods"
final = url %>%
read_html() %>%
html_elements(".article__body-content p") %>%
html_text()
This seems to have worked, but I am trying to combine the results of this code into a single object. For example, the current results look like this:
[1] "Tangled mats of muddy vegetation line the footpaths of Underwood Park, a narrow stripe of green winding along a creek beneath the small volcanic cone of Ōwairaka (Mt Albert) in Auckland, New Zealand. In the water, clumps of sticks and the occasional plastic bag are marooned on protruding rocks and branches."
[2] "A winter storm swept through the city overnight, dropping heavy rain, and Te Auaunga (Oakley Creek), one of the city’s longest urban streams, has overflowed its banks."
[3] "\"But that’s supposed to happen,\" says Julie Fairey, chair of the Puketāpapa local board, who is showing me around Underwood and the neighbouring Walmsley Park."
I would like to make a single object of this text - for example (remove all " "):
final <- "Tangled mats of muddy vegetation line the footpaths of Underwood Park, a narrow stripe of green winding along a creek beneath the small volcanic cone of Ōwairaka (Mt Albert) in Auckland, New Zealand. In the water, clumps of sticks and the occasional plastic bag are marooned on protruding rocks and branches.
A winter storm swept through the city overnight, dropping heavy rain, and Te Auaunga (Oakley Creek), one of the city’s longest urban streams, has overflowed its banks.
But that’s supposed to happen, says Julie Fairey, chair of the Puketāpapa local board, who is showing me around Underwood and the neighbouring Walmsley Park."
When I inspect the results, I initially thought it was a list - but it's actually a character object. Had this been a list, I could have used the "unlist" command. But now I am not sure how to proceed.
Can someone please show me how to proceed?
Thanks!

The output from html_text is a vector of strings. We could join them as a single string with paste and collapse.
library(rvest)
library(magrittr)
final <- url %>%
read_html() %>%
html_elements(".article__body-content p") %>%
html_text() %>%
paste(collapse = "\n")
Now, we check the output
cat(final, sep = "\n")
Tangled mats of muddy vegetation line the footpaths of Underwood Park, a narrow stripe of green winding along a creek beneath the small volcanic cone of Ōwairaka (Mt Albert) in Auckland, New Zealand. In the water, clumps of sticks and the occasional plastic bag are marooned on protruding rocks and branches.
A winter storm swept through the city overnight, dropping heavy rain, and Te Auaunga (Oakley Creek), one of the city’s longest urban streams, has overflowed its banks.
"But that’s supposed to happen," says Julie Fairey, chair of the Puketāpapa local board, who is showing me around Underwood and the neighbouring Walmsley Park.
The connected parks are designed to collect excess stormwater, soak it up like a sponge, and slowly release it back into the creek. The debris left behind is evidence this "secret infrastructure" is working, Fairey says. The two parks are flanked on both sides by public housing developments. "This stuff is designed to flood so that the houses don’t," she says.
It wasn’t always this way, Fairey tells me, as we watch a black shag drying its wings on a rock. Less than a decade ago, the waterway was a concrete-lined culvert that ran through seldom-visited muddy fields. When it flooded, water sloshed into the surrounding suburbs. It collected engine oil, sediment and rubbish and sucked this unhealthy mixture out into the city’s famous harbour, rendering the beaches unsafe to swim.
But in 2016, work began to free Te Auaunga from rigid concrete, and restore it to a more natural, meandering shape. Its banks are now lush with native vegetation like harakeke (flax) and tī kouka (cabbage trees), as well as reeds, ferns and other filtering wetland plants.
The changes have increased this part of the city’s ability to absorb excess rainfall, an attribute sometimes called “sponginess”. Auckland was recently named the most spongy global city in a report by multinational architecture and design firm Arup, thanks to its geography, soil type, and urban design – but experts warn it may not lead the pack for long.
As climate change intensifies extreme weather events worldwide, what can other cities learn from Auckland's successes – and failures?
The connected parks around Te Auaunga creek in Auckland are designed to soak up excess stormwater like a sponge (Credit: Kate Evans)
....

Related

Google rejecting Facebooks json-ld required tags

I am setting up JSON+LD tags on my product pages for Facebooks "Dynamic Ads & Commerce".
https://developers.facebook.com/docs/marketing-api/catalog/reference/
Two tags it states are required:
id
Required for dynamic ads and commerce.
availability
Required for dynamic ads and commerce.
I've added these, but it causes Google to reject my json+ld markup.
Invalid enum value in field 'availability'
1.
2.
How could I please both parties here? If I am adding json+ld markup, it may as well have all required elements to be valid on Google and Facebook (Catalog).
[
{
"#context":"http:\/\/www.schema.org",
"#type":"Product",
"name":"Silentnight Safe Nights Toddler Bedset – 4.5 Tog",
"title":"Silentnight Safe Nights Toddler Bedset – 4.5 Tog",
"url":"http:\/\/myexampledomain.co.uk\/product\/silentnight-safe-nights-toddler-bedset-4-5-tog\/",
"link":"http:\/\/myexampledomain.co.uk\/product\/silentnight-safe-nights-toddler-bedset-4-5-tog\/",
"image":"http:\/\/myexampledomain.co.uk\/app\/uploads\/sites\/3\/2019\/10\/silentnight-safe-nights-toddler-bedset-4.5-tog-pack.jpg",
"image_link":"http:\/\/myexampledomain.co.uk\/app\/uploads\/sites\/3\/2019\/10\/silentnight-safe-nights-toddler-bedset-4.5-tog-pack.jpg",
"description":"The Silentnight Toddler Duvet and Pillow set makes a great first bed set for your little one. The cot bed sized set includes a snuggly duvet and a soft pillow that is specially designed for children. The slim profile of the pillow offers your child just the right amount of support they need. It's important that small children don't overheat in bed, so the light and soft duvet comes in a 4.5 tog weight rating. Both the pillow and duvet are made from a smooth polycotton cover offering breathable comfort. The products are filled with anti-allergy hollowfibre that actively defends against the bacteria and dust mites that can cause allergies providing a cleaner, fresher and altogether a safer option for a good night's sleep. Our anti-allergy fibres are approved by the British Allergy Foundation, which means they have the ultimate seal of approval. Our fibres have been scientifically tested and are proven to reduce or remove allergens from the indoor environment.\nSuitable only for children over 12 months. Both the pillow and duvet are fully machine washable, and thanks to the easy care polycotton covers, the products have great recovery and can be washed time and time again.",
"sku":"506984LS",
"id":17214,
"productID":17214,
"offers":[
{
"#type":"Offer",
"price":"30.99",
"priceCurrency":"GBP",
"url":"http:\/\/myexampledomain.co.uk\/product\/silentnight-safe-nights-toddler-bedset-4-5-tog\/",
"gtin":"5012701506984",
"gtin8":"5012701506984",
"condition":"new",
"availability":"in stock",
"inventoryLevel":54
}
],
"brand":"Silentnight"
}
]

how to add break line in JSON data file

How do I add a break line between each 'step' in my JSON data file in visual studio code?
Below is an example image of how the text is displayed on chrome. below the image is the example code
"Method": [
" 1.Place all the ingredients in a bowl and add 250ml cold water. Mix together with a spoon until you have a spongy mixture, cover with cling film and leave at room temperature overnight",
" 2.Tip the dough onto a floured surface and gently shape into a round. Dust a piece of baking parchment heavily with flour and sit the dough on top. Cover with a tea towel and leave to prove for 1 hr until doubled in size",
" 3.Heat oven to 220C/200C fan/gas 7. Place a flat baking tray on the middle shelf of the oven. Dust the dough with flour and slash with a utility knife.",
" 4.Bake for 25-30 mins until the loaf sounds hollow when tapped on the bottom. Leave the bread to cool completely."
]
If is not related to a particular code, you can select a comma "," and use the shortcut
SHIFT+CTRL+L
to select all the commas. Press the "RIGHT ARROW" to move right after all the commas and lose the selection (to avoid the cancellation of them) and then press "Enter".

Chrome Devtools, copying over a set of answers

I have to do this repeatedly, so I was wondering if there was a working around....
here is a set of amenities for an apartment, they have to be transferred to a larger list containing those amenities by clicking off multiple choice cirlces. Is there away to edit the script to do it all at once>
example
accessible
air conditioning
dishwasher
garage
hardwood floors
parking
patio / balcony
gym
in unit laundry
cats allowed
dogs allowed
pet friendly
basketball court
bathtub
bbq/grill
bike storage
business center
carpet
ceiling fan
clubhouse
game room
granite counters
microwave
oven
package receiving
playground
pool table
range
refrigerator
stainless steel
walk in closets
I think you want to just checkmark all of the checkboxes on the amenities list so something like this will work:
$('div.whitelist-searchable-amenity input[type=checkbox]').each(function(){
$(this).prop('checked', true);
});
https://jsfiddle.net/r62qgou3/
Edit:
I am not sure of what you mean by "copying text to script" but I modified the script to check if the values that you are looking for are within the document. This should search the values of the checkboxes and then you can use your own script to "copy" the value elsewhere. Just add more values to the array if you need more keywords.
x = [
"accessible",
"air conditioning",
"dishwasher",
"garage",
];
$('div.whitelist-searchable-amenity input[type=checkbox]').each(function(){
if(x.indexOf(this.value) > -1)
{
alert("copy here");
}
});

What's stopping these variable's from being defined in my code?

I've been designing this game, and Ive come across a weird problem. Now maybe it's just something simple I've missed or some way I formatted it. When I run my code I get these errors that suggest that none of the variables I've been defining are being declared/defined. On top of that none of the functions seem to run... Should I define text1, button1Name, etc... as Global variable? or is their a better way?
##Project 1 v4
##Structure whole program with base functionality
##Begin with an outline then fill in functions and windows from V2, and V3.
import Tkinter
import random
inventory=[]
playCount=0
def startGame():
##adds name
##button that calls StoryCard
text1="Welcome to Treasure Quest!! The Game that allows you to pick your own destiny! Treasure quest is a very simple game. The story will display on the screen until it reaches an event. At each event you will be shown two choices. Each decision may cause you to leave with more treasure or to die a horrible death... Still like any true or false question on a final exam, you only have a 50/50 chance of ruining your entire life if you do not know! Now that you know how to play, please click the button below to start the game!"
button1= introCard()
button1Name="Play"
button2= win.destroy
button2Name="Quit"
def introCard():
text1="You are the bravest knight in the service of the great kingdom Universitas! The kingdom has long been an icon throughout the world, but now it faces great peril. The king of Universitas has foolishly spent the entirety of the kingdoms fortune shopping online. The only hope for the kingdom, is to find the money to pay off it's debts. Luckily recently some scrolls have been found that describe the locations of hidden treasures. You have been selected to find these treasures. Do you except?"
button1=winCard()
outcome1="You embark upon your quest!"
button1Name="Accept!"
button2=lossCard()
outcome2="The kingdom falls into debt and you die of dysentary... Nice going Oregon Trail..."
button2Name="Decline!"
def storyCard(n):##This function will randomly select a story chunk
##recieves a random int
##tests for true int w/ if then else line
##Story blurbs for these are stored in V2 copy them!
if n ==1:
text1="You come across a dark cave... A dragon is said to lurk within... You enter and see the Holy Sword... How do you take it?"
button1=lossCard()
outcome1="The dragon bakes you to a crisp... Sorry!"
button1Name="Bargain for it!"
button2=winCard()
outcome2="Victory! You sneak past the dragon and make off with the sword!"
button2Name="Steal it!"
#get="Holy Sword"
elif n==2:
text1="You come across a mummys tomb... You see two doors. Take the front entrance or the hidden entrance?"
button1=winCard()
outcome1="The mummy is awake and glad for company! He feeds you tea and sets you on your way with gifts!"
button1Name="Front"
#get="A beautiful glass vase!"
button2=lossCard()
outcome2="The mummy sees you! It screams thief! and shivs you..."
button2Name="Hidden"
elif n==3:
text1="You come across a magic tree inhabited by elves. They ask you to climb up and see their beautiful home."
button1=lossCard()
outcome1="You climb high but slip off a branch and fall to your death. The elves laugh."
button1Name="Climb"
button2=winCard()
outcome2="The elves are perplexed as to why you do not want to see them. They come down and give you a new couch to show off their things."
button2Name="Stay"
#get="A rad couch"
elif n==4:
text1="You come across a cave filled with strange lights! A troll stands guard."
button1=winCard()
outcome1="This is a hip and happening new dwarven nightclub! The troll lets you in because you seem cool! The dwarves give you some rare cave mushrooms. It seems lame but they said the kings a regular and they will go over well. You have a fun night... You drink to much ale and get a late start the next morning though..."
button1Name="Strut in!"
#get="Rare Mushrooms"
button2=winCard()
outcome2="This is actually a hip new dwarven nightclub! The bouncer troll won't let you in though... Oh well! dwarves are hipsters anyways! Gratefull for your company the troll gives you an amulet!"
button2Name="Wait in line."
#get="Sweet Amulet"
elif n==5:
text1="You come across a hut in the woods! Its owned by Merlin! The great wizard starts up conversation and invites you inside!"
button1=lossCard()
outcome1="Insulted, Merlin kills you with an axe... you would have expected magic... but no, Merlin is a psychopath and prefers to murder with axes."
button1Name="Leave"
button2=winCard()
outcome2="He talks about his GOD DAMNED GRANDKIDS FOR FOUR HOURS... He is grateful for you company however and lets you leave with his staff."
button2Name="Enter"
#get="A sweet Staff"
## each if, elif, ect must contain
##Text blurb
##Button 1 function def
##Button 2 function def
##button 1 name
##button 2 name
##Outcome 1 Text
##Outcome 2 Text
def winGame():
text1="CONGRATULATIONS!! You have collected enough treasure to pay off the kingdoms debts! You will forever be known to the people as a great knight! The king is in your debt!"
button1Name="Hooray!"
button1=win.destroy
button2Name="Huzzah!"
button2=win.destroy
def winCard():##Describes how event played out
#inventory.append[get]
playCount+=1
text1= outcome1 or outcome2
if playCount == 5:
button1Name="Onward!"
button1=winGame()
button2Name="Go Forth!"
button2=winGame()
else:
button1Name="Onward!"
button1=storyCard(random.randint(1,5))
button2Name="Go Forth!"
button2=storyCard(random.randint(1,5))
def lossCard():
text1=outcome1 or outcome2
button1Name="Game Over"
button1= win.destroy
button2Name="Game Over"
button2= win.destroy
startGame()
win=Tkinter.Tk()
win.title("TREASURE QUEST!!")
Textlabel=Tkinter.Label(win,text = text1,font=('Times New Roman',12),justify=LEFT,)
Textlabel.pack()
Row2=Tkinter.Frame(win)
Btn1=Tkinter.Button\
(Row2, text=button1Name, command=button1,font=('Times New Roman',12))
Btn2=Tkinter.Button\
(Row2, text=button2Name, command=button2, font=('Times New Roman',12))
Btn1.pack(side='left')
Btn2.pack(side='left')
Row2.pack()
win.mainloop()
When I run the code I get these errors:
Traceback (most recent call last):
File "C:/Users/Logan/Desktop/Project#1V4.py", line 141, in <module>
startGame()
File "C:/Users/Logan/Desktop/Project#1V4.py", line 17, in startGame
button1= introCard()
File "C:/Users/Logan/Desktop/Project#1V4.py", line 26, in introCard
button1=winCard()
File "C:/Users/Logan/Desktop/Project#1V4.py", line 116, in winCard
playCount+=1
UnboundLocalError: local variable 'playCount' referenced before assignment
If you want to change a global variable in a function, you need to use the keyword global as follows -
def winCard():##Describes how event played out
global playCount
#inventory.append[get]
playCount+=1

HTML String in JSON

I know it isn’t the best idea to have html in your JSON but sadly I am not in control of this database or this website and am not given those privileges! I am making google maps markers and one of the values is corrupting the data and not being processed right. I know the issue is in the DESC value, is there some sort of character that isn’t escaped? Because almost all of the other objects in the JSON work just fine besides this one.
{"PHONE":"847-509-2000”,
"LAT":42.15223,
"STATE":"IL”,
"ZIP":60015.0,
"NAME":"DC Sarnies”,
"DESC":"Opening in early May 2011, D.C. Sarnies is a contemporary but casual restaurant
specializing in sandwiches and classic American food with a twist. As well as a
restaurant, we serve as a research and development kitchen for its parent company,
Highland Baking Company. Guest chefs and bakery clients will have the opportunity to try
out new products and let diners provide feedback on the dishes. The menu at D. C. Sarnies
has something for everyone with a wide variety of appetizers, soups, salads, entrees and
signature sandwiches and burgers to choose from. A full bar also gives diners a wide range
of craft beers including more than 25 on tap, wine and cocktails. For more information
visit us on Facebook at D.C. Sarnies or on Twitter DC_Sarnies.”,
"LONG":-87.84241,
"CITY":"Deerfield”,
"ADDR":"649 Lake Cook Road”,
"PHOTO":"DCcrabcakeburger.jpg”}]
jsonlint error message: Parse error on line 74:
...02, "DESC": "Opening in early Ma
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
http://jsonlint.org/ use this website to validate your JSON.
The problem here are the closing quotes you use for strings, they're invalid.
End double quotes wrong. Rest everything is fine and working.
The double quotes at the end of the values are the problem. They're the wrong character.
There are a couple issues:
Different quotes used. ” is different from ".
Multi-line isn't escaped. If you need the line breaks, use \n. Otherwise, just have it one line
The extra ] at the end shouldn't be there
This is what you should have:
{
"PHONE": "847-509-2000",
"LAT": 42.15223,
"STATE": "IL",
"ZIP": 60015,
"NAME": "DC Sarnies",
"DESC": "Opening in early May 2011, D.C. Sarnies is a contemporary but casual restaurant specializing in sandwiches and classic American food with a twist. As well as a restaurant, we serve as a research and development kitchen for its parent company, Highland Baking Company. Guest chefs and bakery clients will have the opportunity to try out new products and let diners provide feedback on the dishes. The menu at D. C. Sarnies has something for everyone with a wide variety of appetizers, soups, salads, entrees and signature sandwiches and burgers to choose from. A full bar also gives diners a wide range of craft beers including more than 25 on tap, wine and cocktails. For more information visit us on Facebook at D.C. Sarnies or on Twitter DC_Sarnies.",
"LONG": -87.84241,
"CITY": "Deerfield",
"ADDR": "649 Lake Cook Road",
"PHOTO": "DCcrabcakeburger.jpg"
}