Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
What is the best way to match words with my sentence? Here is a little sample:
words <- c("apple", "pear", "grape")
sentences <- c("I have an apple and a pear", "Grape is my favorite", "I don't like pear")
The best is if the output could look like:
count sentence
2 "I have an apple and a pear"
1 "Grape is my favorite"
1 "I don't like pear
I have tried using str_count but to no avail. Any help is appreciated!
library(stringr)
str_count(sentences, paste0("(?i)\\b(", paste0(words, collapse = "|"), ")\\b"))
[1] 2 1 1
How this works:
(?i): this makes sure the pattern match is case-insensitive
\\b and \\b make sure the words are matched as words with word boundaries (if \\b is not used you may end up matching something that just contains your words but forms itself a different word such as grapple, which contains apple)
( and )form a non-capturing group, the content of which are the words separated, or combined if you prefer, by the pipe |, a metacharacter for alternation signifying 'OR'.
If you want to have this inside a dataframe:
df <- data.frame(
sentences = sentences,
count = str_count(sentences, paste0("(?i)\\b(", paste0(words, collapse = "|"), ")\\b")))
Result:
df
sentences count
1 I have an apple and a pear 2
2 Grape is my favorite 1
3 I don't like pear 1
Related
This question already has answers here:
Using regex in R to find strings as whole words (but not strings as part of words)
(2 answers)
Closed 2 years ago.
I might be missing something very obvious but how can I write efficient code to get all matches of a singular version of a noun but NOT its plural? for example, I want to match
angel investor
angel
BUT NOT
angels
try angels
If I try
grep("angel ", string)
Then a string with JUST the word
angel
won't match.
Please help!
Use word-boundary markers \\b:
x <- c("angel investor", "angel","angels", "try angels")
grep("\\bangel\\b", x, value = T)
[1] "angel investor" "angel"
You can try the following approach. It still believe there are other excellent ways to solve this problem.
df <- data.frame(obs = 1:4, words = c("angle", "try angles", "angle investor", "angles"))
df %>%
filter(!str_detect(words, "(?<=[ertkgwmnl])s\\b"))
# obs words
# 1 1 angle
# 2 3 angle investor
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I would like to erase characters "(B)" in the code column, so then I could do "summarise" the 'stock_needed'. My data looks like this.
code stock_need
(B)1234 200
(B)5678 240
1234 700
5678 200
0123 200
to be like this.
code stock_need
1234 200
5678 240
1234 700
5678 200
0123 200
How could these "(B)" erased? Thanx in advance
What are other patterns your data has? If it's always "(B)" you can do
sub("\\(B\\)", "", df$code)
#[1] "1234" "5678" "1234" "5678" "0123"
Or if it could be any character do
sub("\\([A-Z]\\)", "", df$code)
You could also extract only the numbers from Code
sub(".*?(\\d+).*", "\\1", df$code)
You might want to wrap output of sub in as.numeric or as.integer to get numeric/integer output.
We can also use readr
readr::parse_number(df$code)
Basically, you need to do two things:
remove the unnecessary part of the string
convert the string to numeric.
Say, we load your data frame:
df <- read.table(header=TRUE, text="code stock_need
(B)1234 200
(B)5678 240
1234 700
5678 200
0123 200 ")
First, we replace the column "code" with something without the parentheses:
df$code <- gsub("\\(B\\)", "", df$code)
Explanation: why the weird \\? Because if we wrote (B), gsub would treat the parentheses in a special way. Parentheses have a special meaning in regular expressions, and the first argument to gsub is a regular expression.
Next, we make a number vector out of it:
df$code <- as.numeric(df$code)
my challenge is to convert ten and one which is in words to numbers as 10 and 1 in the input sentence:
example_input <- paste0("I have ten apple and one orange")
Numbers may change based on user requirement, input sentence can be tokenized:
my_output_toget<-paste("I have 10 apple and 1 orange")
We can pass a key/val pair as replacement in gsubfn to replace those words with numbers
library(english)
library(gsubfn)
gsubfn("\\w+", setNames(as.list(1:10), as.english(1:10)), example_input)
#[1] "I have 10 apple and 1 orange"
textclean is quite a handy possibility for this task:
mgsub(example_input, replace_number(seq_len(10)), seq_len(10))
[1] "I have 10 apple and 1 orange"
You just need to adjust the seq_len() parameter according to the maximum number in your data.
Some examples:
example_input <- c("I have one hundred apple and one orange")
mgsub(example_input, replace_number(seq_len(100)), seq_len(100))
[1] "I have 100 apple and 1 orange"
example_input <- c("I have one tousand apple and one orange")
mgsub(example_input, replace_number(seq_len(1000)), seq_len(1000))
[1] "I have 1 tousand apple and 1 orange"
If you don't know your maximum number beforehand, you can just choose a sufficiently big number.
I wrote an R package to do this - https://github.com/fsingletonthorn/words_to_numbers which should work for more use cases.
devtools::install_github("fsingletonthorn/words_to_numbers")
library(wordstonumbers)
example_input <- "I have ten apple and one orange"
words_to_numbers(example)
[1] "I have 10 apple and 1 orange"
It also works for much more complex cases like
words_to_numbers("The Library of Babel (by Jorge Luis Borges) describes a library that contains all possible four-hundred and ten page books made with a character set of twenty five characters (twenty two letters, as well as spaces, periods, and commas), with eighty lines per book and forty characters per line.")
#> [1] "The Library of Babel (by Jorge Luis Borges) describes a library that contains all possible 410 page books made with a character set of 25 characters (22 letters, as well as spaces, periods, and commas), with 80 lines per book and 40 characters per line."
Or
words_to_numbers("300 billion, 2 hundred and 79 cats")
#> [1] "300000000279 cats"
Less elegantly than Akrun's answer but in base.
nums = c("one","two","three","four","five",
"six","seven","eight","nine","ten")
example_input <- paste0("I have ten apple and one orange")
aux = strsplit(example_input," ")[[1]]
aux[!is.na(match(aux,nums))]=na.omit(match(aux,nums))
example_output = paste(aux,collapse=" ")
example_output
[1] "I have 10 apple and 1 orange"
We first split by spaces, find the matching numbers and change them by the position (coincides with the number itself), then paste it again.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a .csv-file with a column containing book descriptions scraped from the web which I import into R for further analysis. My goal is to extract the protagonists' ages from this column in R, so what I imagine is this:
Match strings like "age" and "-year-old" with a regex
Copy the sentences containing these strings into a new column (so that I can make sure that the sentence is not, for example "In the middle ages 50 people lived in xy"
Extract the numbers (and, if possible some number words) from this column into a new column.
The resulting table (or probably data.frame) would then hopefully look like this
|Description |Sentence |Age
|YY is a novel by Mr. X |The 12-year-old boy| 12
|about a boy. The 12-year|is named Dave. |
|-old boy is named Dave..| |
If you could me help out that would great since my R-skills are still very limited and I have not found a solution for this problem!
Another option if the string contains other numbers/descriptions besides just age, but you only want age.
library(stringr)
description <- "YY is a novel by Mr. X about a boy. The boy is 5 feet tall. The 12-year-old boy is named Dave. Dave is happy. Dave lives at 42 Washington street."
sentence <- str_split(description, "\\.")[[1]][which(grepl("-year-old", unlist(str_split(description, "\\."))))]
> sentence
[1] " The 12-year-old boy is named Dave"
age <- as.numeric(str_extract(description, "\\d+(?=-year-old)"))
> age
[1] 12
Here we use the string "-year-old" to tell us which sentence to pull and then we extract the age that is followed by that string.
You can try the following
library(stringr)
description <- "YY is a novel by Mr. X about a boy. The 12-year-old boy is named Dave. Dave is happy."
sentence <- str_extract(description, pattern = "\\.[^\\.]*[0-9]+[^\\.]*.") %>%
str_replace("^\\. ", "")
> sentence
[1] "The 12-year-old boy is named Dave."
age <- str_extract(sentence, pattern = "[0-9]+")
> age
[1] "12"
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a dataset with unstructured text data.
From the text I want to extract sentences that have the following words:
education_vector <- c("university", "academy", "school", "college")
For example, from the text I am a student at the University of Wyoming. My major is biology. I want to get I am a student at the University of Wyoming.
From the text I love statistics and I enjoy working with numbers. I graduated from Walla Wall Community College I want to get I graduated from Walla Wall Community College. and so on
I tried using grep function but it returned wrong results
Answer modified to select first match.
texts = c("I am a student at the University of Wyoming. My major is biology.",
"I love statistics and I enjoy working with numbers. I graduated from Walla Wall Community College",
"First, I went to the Bowdoin College. Then I went to the University of California.")
gsub(".*?([^\\.]*(university|academy|school|college)[^\\.]*).*",
"\\1", texts, ignore.case=TRUE)
[1] "I am a student at the University of Wyoming"
[2] " I graduated from Walla Wall Community College"
[3] "First, I went to the Bowdoin College"
Explanation:
.*? is a non-greedy match up to the rest of the pattern. This is there to remove any sentences before the relevant sentence.
([^\\.]*(university|academy|school|college)[^\\.]*) matches any string of characters other than a period immediately before and after one of the key words.
.* handles anything after the relevant sentence.
This replaces the entire string with only the relevant part.
Here is a solution using grep
education <- c("university", "academy", "school", "college")
str1 <- "I am a student at the University of Wyoming. My major is biology."
str2 <- "I love statistics and I enjoy working with numbers. I graduated from Walla Wall Community College"
str1 <- tolower(str1) # we use tolower because "university" != "University"
str2 <- tolower(str2)
grep(paste(education, collapse = "|"), unlist(strsplit(str1, "(?<=\\.)\\s+",
perl = TRUE)),
value = TRUE)
grep(paste(education, collapse = "|"), unlist(strsplit(str2, "(?<=\\.)\\s+",
perl = TRUE)),
value = TRUE)