R не удаляет стоп-слова - PullRequest
0 голосов
/ 09 апреля 2020

Я искал твиты и получил следующий код. Этот код должен удалить стоп-слова, цифры и URL-адреса. Было удалено около 1000 слов, но осталось несколько. Когда я получаю лучшие 10 слов, такие слова как не, и я появляюсь. Что-то я делаю неправильно? Стоп-слова присутствуют в тидитексте. Еще один уточняющий вопрос: после противодействия на стоп-словах 3 не осталось, а один остается. Таким образом, противодействие объединяет некоторые стоп-слова.

    crTwts = costaRica %>% 
      mutate(
        # Remove http elements manually
         stripped_text = gsub("http\\S+","",text)
       ) %>% 
       select(stripped_text) %>%
      unnest_tokens(word, stripped_text) %>%
      anti_join(stop_words) %>%
      filter(is.na(as.numeric(word)))

#code to find top 10 words
crTwts %>%
  count(word, sort = TRUE) %>%
  top_n(10) %>%
  mutate(word = reorder(word, n)) %>%
  ggplot(aes(x = word, y = n)) +
  geom_col() +
  xlab(NULL) +
  coord_flip() +
  theme_classic() +
  labs(x = "Count",
       y = "Unique words",
     title = "Unique word counts found in Costa Rica tweets")

Вот данные, которые я получаю: enter image description here

Вот некоторые примеры данных первых 6 твитов в списке costaRica

1 «ЧТО ОНИ ЕЛИ?» Спрашивает @SheilaGunnReid, который сообщает: \ n \ nTrudeau затратил 1200 долларов на семейное питание на рейсах в оба конца в Коста-Рику \ n \ nСМОТРИТЕ здесь: \ n \ n # cdnpoli # TrudeauWorstPM 2 "
[2]" Я клянусь, что вы смотрите ОДИН монтаж Fortnite на Youtube, и внезапно весь ваш рекомендуемый раздел выглядит так: \ nThe Box \ U0001f4e6 \ nВставьте ее Go \ U0001f48d \ nКоста-Рика \ U0001f334 \ nBallin \ U0001f3 nRoxanne \ U0001f495 \ nBlueberry Fay go \ U0001f347 \ nAddison Rae \ U0001f483 "
[3]" Мы только что прошли квалификацию на 2010 W C, мое любимое воспоминание от игры с @USMNT. Сегодня я буду первым время просмотра последнего матча квалификации против Коста-Рики на RFK. Фанатам - спасибо, что вдохновили меня и мотивировали меня на все это этим невероятным жестом ❤️ "
[4]" @Thornburgurr @ AMCx32 @nathanjmartin @RepGregStanton @netf lix Это доказывает, что она не убивала его! У нее не было мотива, но другие люди вокруг него были. У него были связи в мафии в Коста-Рике со многими \ "подругами \". Местный шериф, который хорошо знает дело, сказал, что Кэрол не подозреваемый или даже не заинтересованный человек. "[5]" @anassaifuddin Вы помните \ U0001f60f \ п \ nCorrect! \ U0001f919 \ n \ nАндорра, Коста-Рика и Доминика - примеры стран, в которых нет армии. "
[6]" Вуууу ... должен был уехать в Коста-Рику \ U0001f612 "

head(costaRica)
# A tibble: 6 x 90
  user_id status_id created_at          screen_name text  source
  <chr>   <chr>     <dttm>              <chr>       <chr> <chr> 
1 301896… 12475083… 2020-04-07 12:55:52 RebelNewsO… "WHA… Tweet…
2 159443… 12475862… 2020-04-07 18:05:09 GronKy_     "I s… Hoots…
3 493116… 12475692… 2020-04-07 16:57:47 CharlieDav… We h… Twitt…
4 118886… 12480996… 2020-04-09 04:05:30 Scaldriss   lmfa… Twitt…
5 776571… 12480996… 2020-04-09 04:05:18 annabeccax  twit… Twitt…
6 122272… 12480968… 2020-04-09 03:54:21 PatrickFar… "Cos… Twitt…
# … with 84 more variables: display_text_width <dbl>,
#   reply_to_status_id <chr>, reply_to_user_id <chr>,
#   reply_to_screen_name <chr>, is_quote <lgl>, is_retweet <lgl>,
#   favorite_count <int>, retweet_count <int>, quote_count <int>,
#   reply_count <int>, hashtags <list>, symbols <list>, urls_url <list>,
#   urls_t.co <list>, urls_expanded_url <list>, media_url <list>,
#   media_t.co <list>, media_expanded_url <list>, media_type <list>,
#   ext_media_url <list>, ext_media_t.co <list>,
#   ext_media_expanded_url <list>, ext_media_type <chr>,
#   mentions_user_id <list>, mentions_screen_name <list>, lang <chr>,
#   quoted_status_id <chr>, quoted_text <chr>, quoted_created_at <dttm>,
#   quoted_source <chr>, quoted_favorite_count <int>,
#   quoted_retweet_count <int>, quoted_user_id <chr>,
#   quoted_screen_name <chr>, quoted_name <chr>, quoted_followers_count <int>,
#   quoted_friends_count <int>, quoted_statuses_count <int>,
#   quoted_location <chr>, quoted_description <chr>, quoted_verified <lgl>,
#   retweet_status_id <chr>, retweet_text <chr>, retweet_created_at <dttm>,
#   retweet_source <chr>, retweet_favorite_count <int>,
#   retweet_retweet_count <int>, retweet_user_id <chr>,
#   retweet_screen_name <chr>, retweet_name <chr>,
#   retweet_followers_count <int>, retweet_friends_count <int>,
#   retweet_statuses_count <int>, retweet_location <chr>,
#   retweet_description <chr>, retweet_verified <lgl>, place_url <chr>,
#   place_name <chr>, place_full_name <chr>, place_type <chr>, country <chr>,
#   country_code <chr>, geo_coords <list>, coords_coords <list>,
#   bbox_coords <list>, status_url <chr>, name <chr>, location <chr>,
#   description <chr>, url <chr>, protected <lgl>, followers_count <int>,
#   friends_count <int>, listed_count <int>, statuses_count <int>,
#   favourites_count <int>, account_created_at <dttm>, verified <lgl>,
#   profile_url <chr>, profile_expanded_url <chr>, account_lang <lgl>,
#   profile_banner_url <chr>, profile_background_url <chr>,
#   profile_image_url <chr>                                                                                       

РЕШЕНИЕ Существуют разные кавычки («против»). Мы должны выложить фигурную кавычку для прямой кавычки, и она находит слова в стоп-словах.

Мой новый код

crTwts = costaRica %>% 
  mutate(
    # Remove http elements manually
    stripped_text = gsub("http\\S+","",text)
  ) %>% 
  mutate(stripped_text = gsub("’", "'", stripped_text, ignore.case = TRUE))  %>%
  select(stripped_text)  %>%
  unnest_tokens(word, stripped_text) %>%
  anti_join(all_cr_stop_words) %>%
  filter(is.na(as.numeric(word)))

1 Ответ

1 голос
/ 09 апреля 2020

В будущем, пожалуйста, включите пример данных в свой вопрос. Но для этого попробуйте:

crTwts <- 
  costaRica %>% 
  mutate(
    # Remove http elements manually
    stripped_text = gsub("http.*|\\d+","",text)
  ) %>% 
  select(stripped_text) %>%
  unnest_tokens(word, stripped_text) %>%
  filter(!(gsub("'", "", word) %in% gsub("'", "", stop_words$word)) & word != "")

Пакеты, необходимые выше:

# Install pacakges if they are not already installed:
necessary_packages <- c("tidytext", "dplyr", "ggplot2")

# Create a vector containing the names of any packages needing installation:
new_packages <- necessary_packages[!(necessary_packages %in%
                                       installed.packages()[, "Package"])]

# If the vector has more than 0 values, install the new pacakges
# (and their) associated dependencies:
if (length(new_packages) > 0) {
  install.packages(new_packages, dependencies = TRUE)
}

# Initialise the packages in the session:
lapply(necessary_packages, require, character.only = TRUE)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...