首页 > 解决方案 > 使用 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

标签: rtidyversetidytext

解决方案


我们也可以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

推荐阅读