In JavaScript, template literals may be used to insert a dynamic value into text.
Here is an example:
const name = "John";
console.log(`Hello ${name}, how are you?`;)
This would print Hello John, how are you? to the console.
An approach to this in R would be to use paste0
name = "John"
print(paste0("Hello ", name, ", how are you?"))
This becomes quite a hassle if you are dealing with long texts that require multiple dynamic variables.
What are some alternatives to template literals in R?
You can also use str_glue from the stringr package to directly refer to an R object:
library(stringr)
name = "John"
str_glue("Hello {name}, how are you?")
# Hello John, how are you?
Take a look at the versatile sprintf()-function
name = "John"
sprintf( "Hello %s, how are you", name )
#[1] "Hello John, how are you"
Related
I am working on parsing structured text files by pyparsing and I have a problem judging whitespace or numerical number. My file looks like this:
RECORD 0001
TITLE (Main Reference Title)
AUTHOR (M.Brown)
Some files have more than one author then
RECORD 0002
TITLE (Main Reference Title 1)
AUTHOR 1(S.Red)
2(B.White)
I would like to parse files and convert them into dictionary format.
{"RECORD": "001",
"TITLE": "Main Reference Title 1",
"AUTHOR": {"1": "M.Brown"}
}
{"RECORD": "002",
"TITLE": "Main Reference Title 2",
"AUTHOR": {"1": "S.Red", "2": "B.White"}
}
I tried to parse the AUTHOR field by pyparsing (tried both 2.4.7 and 3.0.0b3). Following is the simplified version of my code.
from pyparsing import *
flag = White(" ",exact=1).set_parse_action(replace_with("1")) | Word(nums,exact=1)
flaged_field = Group(flag + restOfLine)
next_line = White(" ",exact=8).suppress() + flaged_field
authors_columns = Keyword("AUTHOR").suppress() +\
White(" ",exact=2).suppress() +\.
flaged_field +\ # parse first row
ZeroOrMore(next_line) # parse next row
authors = authors_columns.search_string(f)
, where 'f' contains all lines read from the file. With this code, I only could parse the author's names with numbering flags.
[]
[[['1', '(S.Red)'],['2','(B.White)']]]
However, if I only parse with whitespace
flag = White(" ",exact=1).set_parse_action(replace_with("1"))
it worked correctly for the files without numbering flags.
['1', '(M.Brown)']
[]
The number (or whitespace) in [9:10] has a meaning in my format and want to judge if it is a whitespace or a numerical number (limited up to 9). I also replaced "|" to "^", and replaced the order, and tried
flag = Word(nums+" ")
, too, but neither of the cases works for me. Why judge White(" ") or Word(nums) doesn't work with my code? Could someone help me or give me an idea to solve this?
This was solved by adding leave_whitespace().
flag = (White(" ",exact=1).set_parse_action(replace_with("0")) | Word(nums,exact=1)).leave_whitespace()
Ok so basically I have the following code:
name=raw_input("What is your name?")
quest=raw_input("What is your quest?")
print ("As so your name is %s, your quest is %s ") %(name,quest)
This runs perfection in Python 2.7.9
I have tried to run this same exact code in Python 3.4.2 and it does't work (figured), so I modified it to this thinking it would work:
name=input("What is your name?")
quest=input("What is your quest?")
print ("As so your name is %s, your quest is %s ") %(name,quest)
And this:
name=input("What is your name?")
quest=input("What is your quest?")
print ("As so your name is {}, your quest is {} ") .format(name,quest)
And of course that didn't work either, I have searched for over an hour now multiple sites, what am I missing here? How do you do this in Python 3.4.2, all I keep getting is sites and answers showing you the first way (I listed), and all it does is work on the older version python 2.
Thanks
print is a function in Python 3. Thus, doing print(...).format(...) is effectively trying to format the return value of the print() call, which is None.
Call .format() on the string you want formatted instead:
print("As so your name is {}, your quest is {} ".format(name,quest))
Your modified code was nearly right, you just needed to move a bracket to apply the % operator to the string instead of the print function result.
So change this:
print ("As so your name is %s, your quest is %s ") % (name, quest)
to this:
print ("As so your name is %s, your quest is %s " % (name, quest))
and it runs fine in Python 3.
I need to remove punctuation from the text. I am using tm package but the catch is :
eg: the text is something like this:
data <- "I am a, new comer","to r,"please help","me:out","here"
now when I run
library(tm)
data<-removePunctuation(data)
in my code, the result is :
I am a new comerto rplease helpmeouthere
but what I expect is:
I am a new comer to r please help me out here
Here's how I take your question, and an answer that is very close to #David Arenburg's in the comment above.
data <- '"I am a, new comer","to r,"please help","me:out","here"'
gsub('[[:punct:] ]+',' ',data)
[1] " I am a new comer to r please help me out here "
The extra space after [:punct:] is to add spaces to the string and the + matches one or more sequential items in the regular expression. This has the side effect, desirable in some cases, of shortening any sequence of spaces to a single space.
If you had something like
string <- "hello,you"
> string
[1] "hello,you"
You could do this:
> gsub(",", "", string)
[1] "helloyou"
It replaces the "," with "" in the variable called string
I know you can escape special characters with "\"'s, but I'm interesting in creating commands that will go to the terminal that include special characters, and these cannot read the backslashes well.
As a simplified example, I'd like to have a command that looks like:
echo hello "w" or'l'd
Which could be achieved by something like
system(command="""echo hello "w" or'l'd""")
But R doesn't handle triple quotes. Is there another way? Even catching the output from cat() would be ok. e.g. newCommand = cat("echo hello \"w\" orld")
Thanks.
You can escape the " with \". I would also use shQuote if your intention is to run system commands. It takes care of the relevant escaping for you...
shQuote( "hello \"w\" orld" , type = "cmd" )
#[1] "\"hello \\\"w\\\" orld\""
You should be aware that what you see on-screen in the R interpreter is not exactly what the shell will see.. e.g.
paste0( "echo " , shQuote( "hello \"w\" orld" , type = "sh") )
#[1] "echo 'hello \"w\" orld'"
system( paste0( "echo " , shQuote( "hello \"w\" orld" , type = "sh") ) )
#hello "w" orld
You can use single quotes:
system(command='echo hello "w" orld')
Raw characters were introduced in R 4.0.0, released 2020-04-27:
There is a new syntax for specifying raw character constants similar
to the one used in C++: r"(...)" with ... any character sequence not
containing the sequence ‘)"’. This makes it easier to write strings
that contain backslashes or both single and double quotes. For more
details see ?Quotes.
> cat(r"(echo hello "w" or'l'd)")
echo hello "w" or'l'd
library(glue)
glue('echo hello "w" or{single_quote("l")}d')
OR
glue('echo hello "w" or{l}d', l = "'l'")
Okay, so I already have a Pipe where I extracted the string I need from item.description, using the Loop and String Regex modules, and am emitting the results with the "emit results" option. Now, where do I go from here?
EDIT: Since an example was requested, here is one:
The item.title is "NBA Game: Lakers vs. Clippers" and the item.description is "The game went into overtime. The final score was 110-90." So the I'd like to extract "110-90" and copy it to the title, where it would then be "... Clippers (110-90)".
1/ Put the score in "scorefield"
Rename operator: [item.description] [COPY AS] [scorefield]
Regex operator : in [scorefield] replace [.*\(([^)]+)\).*] with [$1]
2/ Append score to item.title
Regex operator : in [item.title] replace [($)] with [$1 ${scorefield}]
Nota :
In the above lines the outside square brackets are to be omitted unless noted otherwise
For complements :
http://beckism.com/2009/04/yahoo_pipes/
https://brooksbayne.wordpress.com/2009/01/11/using-regular-expressions-with-yahoo-pipes/