使用R按顺序交换字符串中的每个字母
对于那些DnD的粉丝们,我最近发现了语法学家的戒指。因此,我试图创建一个快速脚本,用于基于从输入字符串交换字母来生成合理单词列表。例如,我想输入“魔法师之手”,让程序返回一个列表或数据帧,其中读取使用R按顺序交换字符串中的每个字母,r,string,R,String,对于那些DnD的粉丝们,我最近发现了语法学家的戒指。因此,我试图创建一个快速脚本,用于基于从输入字符串交换字母来生成合理单词列表。例如,我想输入“魔法师之手”,让程序返回一个列表或数据帧,其中读取 cage hand ...yada yada ... mage band mage land ...yada yada ... mage bang 到目前为止,我只做到了这一点: dictionary<-data.frame(DICTIONARY) spell.suggester<-f
cage hand
...yada yada ...
mage band
mage land
...yada yada ...
mage bang
到目前为止,我只做到了这一点:
dictionary<-data.frame(DICTIONARY)
spell.suggester<-function(x){
for (i in 1:nchar(x)) {
for (k in 1:length(letters)) {
res1<-gsub(pattern = x[i] ,replace = letters[k], x)
res2<-grep("\\bres1\\b",dictionary[,1],value = F)
if_else(res2>1,print(grep("\\bres1\\b",dictionary[,1],value = T)),"nonsense")
return()
}
}
}
spell.suggester(x = "mage hand")
我在堆栈中没有找到使用R的任何答案。有人能帮我提供一些建议和指导吗?您这里的主要问题是,您试图为字符串的每个字母编制索引,而R不希望您这样做-它将字符串作为一个整体值来处理,因此尝试为字母编制索引失败 要解决这个问题,您可以使用
strsplit
将字符串转换为单个字符的向量,您可以像正常情况一样索引这些字符
你的第二期词典搜索似乎有点过于复杂;您可以使用%中的%检查向量中是否存在值
下面的代码展示了如何实现这一点的一个简单示例;它只适用于单个单词,并且依赖于你有一本像样的字典来检查有效单词
# minimal example of valid word list
dictionary <- c("vane", "sane", "pane", "cane",
"bone", "bans", "bate", "bale")
spell.suggester<-function(spell){
#Split spell into a vector of single characters
spell_letters <- strsplit(spell,"")[[1]]
# Once for each letter in spell
for (i in 1:nchar(spell)) {
# Once for each letter in letters
for (k in 1:length(letters)) {
#If the letter isn't a space
if (spell_letters[i] != " "){
# Create a new word by changing one letter
word <-gsub(pattern = spell_letters[i] ,replace = letters[k], spell)
# If the word is in the list of valid words
if (word %in% dictionary){
# print the possibility
print(word)
}
}
}
}
}
spell.suggester(spell="bane")
#有效单词列表的最小示例
字典似乎您需要gsub中的三个参数,这对我很有用:gsub(pattern=“a”,x=“b”,replacement=“c”)
谢谢您指出这个输入错误,我将对我的问题“\\bres1\\b”进行调整。您可能正在尝试使用res1
构造字符串。请查看该功能的paste0
。另请参见字符串模板s的glue
package。感谢您指出此错误,我将对我的问题进行调整
# minimal example of valid word list
dictionary <- c("vane", "sane", "pane", "cane",
"bone", "bans", "bate", "bale")
spell.suggester<-function(spell){
#Split spell into a vector of single characters
spell_letters <- strsplit(spell,"")[[1]]
# Once for each letter in spell
for (i in 1:nchar(spell)) {
# Once for each letter in letters
for (k in 1:length(letters)) {
#If the letter isn't a space
if (spell_letters[i] != " "){
# Create a new word by changing one letter
word <-gsub(pattern = spell_letters[i] ,replace = letters[k], spell)
# If the word is in the list of valid words
if (word %in% dictionary){
# print the possibility
print(word)
}
}
}
}
}
spell.suggester(spell="bane")