r - 使用 tidytext::unnest_tokens() 制作 ngram 时如何保留某些特殊字符?
问题描述
当提到特定大小的事物时,我正在处理具有诸如“3/8”和“5/8”之类的字符组合的文本,并且我正在制作二元组来帮助分析文本。我不想删除“/”字符,但没有找到方法来做到这一点。这是一个例子:
library(tidyverse)
library(tidytext)
tibble(text="My example is 3/8 pipe and 5/8 wrench") %>%
unnest_tokens(bigrams,text,token="ngrams",n=2)
这是输出:
# A tibble: 9 x 1
bigrams
<chr>
1 my example
2 example is
3 is 3
4 3 8
5 8 pipe
6 pipe and
7 and 5
8 5 8
9 8 wrench
谢谢您的意见。
编辑:我找到了一种解决方法,但它很粗糙,很想听到更优雅的解决方案。
library(tidyverse)
library(tidytext)
library(stringr)
tibble(text="My example is 3/8 pipe and 5/8 wrench") %>%
mutate(text=str_replace_all(text,"\\/","forwardslash")) %>%
unnest_tokens(bigrams,text,token="ngrams",n=2) %>%
mutate(bigrams=str_replace_all(bigrams,"forwardslash","/"))
输出:
# A tibble: 7 x 1
bigrams
<chr>
1 my example
2 example is
3 is 3/8
4 3/8 pipe
5 pipe and
6 and 5/8
7 5/8 wrench
解决方案
我们也可以chartr
用于更换
library(tidytext)
tibble(text="My example is 3/8 pipe and 5/8 wrench") %>%
mutate(text = chartr("/", "_", text)) %>%
unnest_tokens(bigrams, text, token = "ngrams", n = 2) %>%
mutate(bigrams = chartr("_", "/", bigrams))
-输出
# A tibble: 7 × 1
bigrams
<chr>
1 my example
2 example is
3 is 3/8
4 3/8 pipe
5 pipe and
6 and 5/8
7 5/8 wrench
推荐阅读
- php - 在后台codeigniter中调用函数
- mysql - 使用随机数据填充表时如何避免插入具有重复主键值的元组
- apache - Apache 作为代理使用相同的 URL 和不同应用程序的子路由
- azure - 使用 Azure DevOps 将 Umbraco v8 应用程序部署到 Azure
- r - 具有连续变量的有序逻辑回归 - 缩放
- mysql - InnoDB 行操作的增加
- python-3.x - 如何将多个字典写入 csv 文件?[Python]
- jquery - 我的代码有问题,我希望在密码字段为空时不提交表单
- debugging - 拔出 JTAG 如何(不重新启动但)解冻在 JTAG 插入之前冻结的设备?
- variables - 为什么这个函数作为全局变量运行,而不是作为局部变量运行?