首页 > 解决方案 > 使用 .csv 文件中的数据替换 .txt 文件中的单词

问题描述

我有一个 .csv(我们​​称它为 TL.csv)文件,其中包含两列遵循此模式的数据:

A1 B1
A2 B2
A3 B3
etc

我想要一个在 R Studio 中运行的脚本,它将运行各种 .txt 文件(让我们使用假设文件 TEST.txt)并将所有 A1 实例替换为 B1,将所有 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 的天赋/统计部分时,我想将其替换为

[[span class="hover"]] Talent [[span]] Definition [[/span]][[/span]]

所以我的球员或我可以将鼠标悬停在天赋上,无需查找即可查看定义。

如果有人可以帮助我编写这段代码,我将不胜感激。

标签: rcsvreplace

解决方案


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"

推荐阅读