我的数据集包含很多文本。完全用外语写的文本会被删除。现在,所有的文本都是用英语写的,但有些文本中有翻译,例如,一个双语的人,除了英语文本之外,还将英语文本下面的英语文本翻译成了非英语文本。我想把文本中的那些部分过滤掉。
文本都在一个变量中。我曾试图取消测试这些文本(使用tidytext的unnest_tokens函数(,并使用textcat包来检测未测试单词的语言,但这给了我最不一致的语言,从法语到斯洛文尼亚语,尽管相应的单词是英语。
我用于此不测试和检测的代码如下(为了性能起见,我创建了一个示例(:
text_unnesting_tokens <- MyDF %>% tidytext::unnest_tokens(word, text)
sample <- text_unnesting_tokens[sample(nrow(text_unnesting_tokens), 5000), ]
sample$language <- textcat(sample$word, p = textcat::TC_char_profiles)
如果您想使用textcat::textcat()
,您应该在标记化之前执行,因为它是基于整体文本,而不是单个标记。首先使用textcat()
识别语言,然后标记化:
library(tidyverse)
library(tidytext)
library(textcat)
library(hcandersenr)
fir_tree <- hca_fairytales() %>%
filter(book == "The fir tree")
## how many lines per language?
fir_tree %>%
count(language)
#> # A tibble: 5 x 2
#> language n
#> <chr> <int>
#> 1 Danish 227
#> 2 English 253
#> 3 French 227
#> 4 German 262
#> 5 Spanish 261
## how many lines per detected language?
fir_tree %>%
mutate(detected_lang = textcat(text)) %>%
count(detected_lang, sort = TRUE)
#> # A tibble: 30 x 2
#> detected_lang n
#> <chr> <int>
#> 1 german 257
#> 2 spanish 238
#> 3 french 215
#> 4 english 181
#> 5 danish 138
#> 6 norwegian 80
#> 7 scots 60
#> 8 portuguese 7
#> 9 swedish 6
#> 10 middle_frisian 5
#> # … with 20 more rows
## now detect language + tokenize
fir_tree %>%
mutate(detected_lang = textcat(text)) %>%
unnest_tokens(word, text)
#> # A tibble: 14,850 x 4
#> book language detected_lang word
#> <chr> <chr> <chr> <chr>
#> 1 The fir tree Danish danish ude
#> 2 The fir tree Danish danish i
#> 3 The fir tree Danish danish skoven
#> 4 The fir tree Danish danish stod
#> 5 The fir tree Danish danish der
#> 6 The fir tree Danish danish sådant
#> 7 The fir tree Danish danish et
#> 8 The fir tree Danish danish nydeligt
#> 9 The fir tree Danish danish grantræ
#> 10 The fir tree Danish danish det
#> # … with 14,840 more rows
由reprex包(v0.3.0(创建于2020-04-30