logo
down
shadow

Replace space between two words with an underscore in a vector


Replace space between two words with an underscore in a vector

By : Abdghafour Siraj-Edd
Date : November 21 2020, 07:01 PM
will be helpful for those in need I have words, Genus species, and I want an underscore to replace the space between the two strings in R , You should use gsub:
code :
data$species <- gsub(" ", "_", data$species)


Share : facebook icon twitter icon
Replace underscore between words (reg.exp)

Replace underscore between words (reg.exp)


By : user1822305
Date : March 29 2020, 07:55 AM
this one helps. I need a regular expression to solve the following problem (links to similar problems is also appreciated, related tutorials etc.): , This should work in Javascript:
code :
var newString = oldString.replace(/([^_].*?)_(?=[^_|^\s])/g,"$1 ");
var newString = oldString.replace(/([^_|\s].*?)_(?=[^_|^s])/g,"$1 ");
var arrayString = oldString.replace(/^(_+)(.*?)(_+)$/g,"$1;$2;$3");
var a = arrayString.split(";");
var newString = a[0]+a[1].replace(/_/g," ")+a[2];
Replace words that start from underscore

Replace words that start from underscore


By : sumalatha Manthu
Date : March 29 2020, 07:55 AM
To fix this issue (\b_\w+) - \b matches on a word boundary.
Visual studio find & replace with regex, replace space with underscore

Visual studio find & replace with regex, replace space with underscore


By : keygrafikdesign
Date : March 29 2020, 07:55 AM
like below fixes the issue In VS 2010, to replace a space between alphanumeric characters you could use
Find What {:a} {:a}
Fastest way to replace space for underscore for a list of words in text

Fastest way to replace space for underscore for a list of words in text


By : 3XK
Date : March 29 2020, 07:55 AM
I hope this helps you . It may be better to split the words, mapping the words from the start of the phrase to the full phrase, if you need the largest, instead of checking every item in the dict you just need to sort the phrases that appear by length:
code :
from collections import defaultdict

def get_phrases(fle):
    phrase_dict = defaultdict(list)
    with open(fle) as ph:
        for line in map(str.rstrip, ph):
            k, _, phr = line.partition(" ")
            phrase_dict[k].append(line)
        return phrase_dict

from itertools import chain


def replace(fle, dct):
    with open(fle) as f:
        for line in f:
            phrases = sorted(chain.from_iterable(dct[word] for word in line.split() 
                             if word in dct) ,reverse=1, key=len)
            for phr in phrases:
                  line = line.replace(phr, phr.replace(" ", "_"))
            yield line
In [10]: cat out.txt
This is a sentence that contains multiple phrases that I need to replace with phrases with underscores, e.g. social political philosophy with political philosophy under the branch of philosophy and some computational linguistics where the cognitive linguistics and psycho cognitive linguistics appears with linguistics
In [11]: cat phrases.txt
cognitive linguistics
psycho cognitive linguistics
socio political philosophy
political philosophy
computational linguistics
linguistics
philosophy
social political philosophy
In [12]: list(replace("out.txt",get_phrases("phrases.txt")))
Out[12]: ['This is a sentence that contains multiple phrases that I need to replace with phrases with underscores, e.g. social_political_philosophy with political_philosophy under the branch of philosophy and some computational_linguistics where the cognitive_linguistics and psycho_cognitive_linguistics appears with linguistics']
def repl(x):
    if x:
        return x.group().replace(" ", "_")
    return x


def replace_re(fle, dct):
    with open(fle) as f:
        for line in f:
            spl = set(line.split())
            phrases = chain.from_iterable(dct[word] for word in spl if word in dct)
            line = re.sub("|".join(phrases), repl, line)
            yield line


def replace_re2(fle, dct):
    cached = {}
    with open(fle) as f:
        for line in f:
            phrases = tuple(chain.from_iterable(dct[word] for word in set(line.split()) if word in dct))
            if phrases not in cached:
                r = re.compile("|".join(phrases))
                cached[phrases] = r
                line = r.sub(repl, line)
            else:
                line = cached[phrases].sub(repl, line)
            yield line
Replace only space between two words, not between words and symbol or words and numbers

Replace only space between two words, not between words and symbol or words and numbers


By : user3185765
Date : March 29 2020, 07:55 AM
wish of those help I'm trying to use the stringr package in R to identify space(s) between words but not space(s) between words and symbols (or vice versa) or words and numbers (or vice versa), or symbols and numbers. , You may use
code :
str_replace_all(x, "(?<=\\p{L})\\s(?=\\p{L})", "_")
gsub("(?<=\\p{L})\\s(?=\\p{L})", "_", x, perl=TRUE)
str_replace_all(x, "(?<=\\p{L})\\s+(?=\\p{L})", "_")
gsub("(?<=\\p{L})\\s+(?=\\p{L})", "_", x, perl=TRUE)
Related Posts Related Posts :
  • How do I interpret rpart splits on factor variables when building classification trees in R?
  • How to better create stacked bar graphs with multiple variables from ggplot2?
  • Building all combinations of a vector - looking for a nicer way
  • Fetching comments from tweets of a single user in R
  • Alternate tick labels in grouped ggplot to avoid overlap in R
  • NSE in tidyverse with select()
  • How to split a table by one column in R?
  • writing to a dataframe from a for-loop in R
  • How to create a data.frame with a unknown number of columns?
  • R dplyr's group_by consider empty groups as well
  • injection from R^d to [0,1]^d
  • Parsing a vector in R
  • What is 'n' column in the below output?
  • Lattice: multiple plots in one window?
  • R - If statement function to set value of new column
  • Avoiding seasonality assumption for stl() or decompose() in R
  • Cannot add new library path to .libPaths()
  • What's the higher-performance alternative to for-loops for subsetting data by group-id?
  • package ‘fpc’ is not available (for R version 3.5.3)
  • R - Convert CHR to Date
  • Get characters after and before a pattern match in R
  • Subtract even columns from odd ones in a data frame
  • Changing numbers in a string
  • Using && for character vectors in r
  • Why am I getting this New York output alone?
  • Saving H2o data frame
  • In R, when using named rows, can a sparse matrix column be added (concatenated) to another sparse matrix?
  • How to convert hourly data to 6/12/24 hourly data
  • Crosstab with multiple items
  • count words with for loop in R
  • Replace cos^..(...) by (cos(...))^
  • Is there a Pair-Wise PostHoc Comparisons for the Chi-Square Test in R?
  • How do I specify random factors in R?
  • ANOVA with 3 fixed factors in R
  • convert numbers written in words to numbers using R programming
  • In R, how can I look up a value in one column based on an interval in adjoining columns that includes values I want to m
  • Convert Date in YYYYMM to YYYY-MM-DD
  • grep does not show all the indices, only [1]1
  • Normalizing a dataframe having several conditions, R
  • What is the equivalent of "everything()" operator in "data.table"?
  • The colors in ggplot do not correspond to the colors in the legend
  • How to add to each column of dataframe value from named vector?
  • Losing data while saving csv character file
  • How to target arbitrary HTML attribute containing space in R?
  • Iterate over a column and find the sum
  • reference another column with tidyeval in filter
  • How to create a new variable by comparing two other variables
  • Retrieving elements that are occurring after adding a fixed number from a start element in a vector
  • Get total mean for variables nested in a list of lists of lists
  • Render Xaringan Rmd when using _site.yml file
  • Regex: matching multiple patterns and getting middle of string
  • removing for loop with sample function
  • R: scraping additional data after POST only works for first page
  • R - Add ticks on top of plot with levels in variable?
  • How to avoid factors in R when reading csv data
  • Meaning of :: syntax
  • How to get month and week of the month from year and week no in R?
  • Can you save R code files with .RData objects for version control?
  • How to connect points of two different plots to each other using ggplot in R?
  • Is there an R function for finding the value below specific value
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk