gpt4 book ai didi

R 在空行上拆分文本

转载 作者:行者123 更新时间:2023-12-02 15:18:24 24 4
gpt4 key购买 nike

我有一个很长的文件,看起来像这样:

"Ach! Hans, Run!" 
2RRGG
Enchantment
At the beginning of your upkeep, you may say "Ach! Hans, run! It's the . . ." and name a creature card. If you do, search your library for the named card, put it into play, then shuffle your library. That creature has haste. Remove it from the game at end of turn.
UNH-R

A Display of My Dark Power
Scheme
When you set this scheme in motion, until your next turn, whenever a player taps a land for mana, that player adds one mana to his or her mana pool of any type that land produced.
ARC-C

AErathi Berserker
2RRR
Creature -- Human Berserker
2/4
Rampage 3 (Whenever this creature becomes blocked, it gets +3/+3 until end of turn for each creature blocking it beyond the first.)
LE-U

AEther Adept
1UU
Creature -- Human Wizard
2/2
When AEther Adept enters the battlefield, return target creature to its owner's hand.
M11-C, M12-C, DDM-C

...

我想将此文件加载到 data.frame 或矢量“oracle”中,由每个空行(实际上是一个空格和一个换行符)分割,以便

oracle[1] 

输出类似

"Ach! Hans, Run!" 2RRGG Enchantment At the beginning of your upkeep, you may say "Ach! Hans, run! It's the . . ." and name a creature card. If you do, search your library for the named card, put it into play, then shuffle your library. That creature has haste. Remove it from the game at end of turn. UNH-R

我试过这样的代码

oracle <- read.table(file = "All Sets.txt", quote = "", sep="\n")

以及 scan(),但是

oracle[1]

给出非常长的、不需要的输出。

谢谢!

最佳答案

根据您编辑的问题试试这个:

oracle <- readLines("BenYoung2.txt")
nvec <- length(oracle)
breaks <- which(! nzchar(oracle))
nbreaks <- length(breaks)
if (breaks[nbreaks] < nvec) {
breaks <- c(breaks, nvec + 1L)
nbreaks <- nbreaks + 1L
}
if (nbreaks > 0L) {
oracle <- mapply(function(a,b) paste(oracle[a:b], collapse = " "),
c(1L, 1L + breaks[-nbreaks]),
breaks - 1L)
}


oracle[1]
# [1] "\"Ach! Hans, Run!\" 2RRGG Enchantment At the beginning of your upkeep, you may say \"Ach! Hans, run! It's the . . .\" and name a creature card. If you do, search your library for the named card, put it into play, then shuffle your library. That creature has haste. Remove it from the game at end of turn. UNH-R"

编辑:尽管如果您始终将真正的空行作为分隔符,这会很好地工作,但您可以使用此行来代替仅使用空白的行:

breaks <- which(grepl("^[[:space:]]*$", oracle))

当行真正为空时,这会给出相同的结果。

关于R 在空行上拆分文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38958597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com