我的数据集包含很多文本。完全用外文撰写的文本被删除。现在,所有的文本都是用英语写的,但有些文本中还有翻译,例如,某人是双语的,除了英语文本外,还在英语文本下面翻译了非英语文本中的英语文本。我想把这些部分的文本过滤掉。
这些文本都在一个变量内。我曾试着对这些文本进行解嵌(使用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()
你应该这样做 之前 tokenization,因为它是基于整个文本的组合,而不是基于单个标记。第一次使用 textcat()
识别语言和 然后 tokenize。
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
于2020-04-30创建。重读包 (v0.3.0)