我有一个.csv(让我们称之为TL.csv)文件,其中包含两列符合此模式的数据:
A1 B1
A2 B2
A3 B3
etc
我想在R Studio中运行一个脚本,它将运行各种.txt文件(让我们使用一个假设的文件,TEST.txt)并用B1替换A1的所有实例,A2的所有实例都用B2, A3与B3等的所有实例,并为整个文档执行此操作。然后我想要修改.txt文件(比如名为TESTOUTPUT.txt)。
到目前为止,凭借我极其简陋的技能,我已经能够拼凑出一些可能不会起作用的不完整代码,但我觉得值得尝试。
所以我放了我的TL.csv文件和TEST.txt
setwd("C:/Users/Alex/Documents/RWork")
TLData<-read.csv(file="TL.csv", header=TRUE, sep=",")
对于上下文我有一个wikidot网站,我用它来保存有关我运行的桌面RPG的信息,我希望能够在我写页面时为术语添加hovertext定义。就像当一个天才出现在NPC的talent / stats部分时,我想用
替换它[[span class="hover"]] Talent [[span]] Definition [[/span]][[/span]]
所以我的玩家或者我可以将鼠标悬停在Talent上并查看定义而无需查找。
如果有人能帮我写这段代码,我会非常感激。
答案 0 :(得分:0)
library(readr)
library(stringr)
notional_csv <- c(
"A1, B1
A2, B2
A3, B3"
)
df <- notional_csv %>% # replace with path to your .csv
read_csv(col_names = c("text_to_replace", "replacement")) # you should already have column names
df
#> # A tibble: 3 x 2
#> text_to_replace replacement
#> <chr> <chr>
#> 1 A1 B1
#> 2 A2 B2
#> 3 A3 B3
# the .csv is read in as a data frame, use it to create a named vector:
replacements <- df$replacement %>%
`names<-`(df$text_to_replace)
replacements
#> A1 A2 A3
#> "B1" "B2" "B3"
# an example string
string <- "This is the A1 sentence. This is the A2 sentence. Here's the A3 sentence"
string
#> [1] "This is the A1 sentence. This is the A2 sentence. Here's the A3 sentence"
# replace based on the named values in the replacements vector
new_string <- str_replace_all(string, replacements)
new_string
#> [1] "This is the B1 sentence. This is the B2 sentence. Here's the B3 sentence"
# whatever the path/directory is you're using
temp_path <- paste0(tempdir(), "/TEST.txt")
# write the string to TEST.txt
write_lines(new_string, path = temp_path)
# Check it by reading TEST.txt back into R
read_lines(temp_path)
#> [1] "This is the B1 sentence. This is the B2 sentence. Here's the B3 sentence"