-1
A
回答
2
這是我設計的一個功能。請注意,我基於空格分割字符串,刪除了任何空白或空白,我也刪除了「。」,並將所有大寫字母轉換爲小寫字母。最後,如果有平局,我總是會報第一個字。這些假設你應該考慮爲你自己的分析。
# Create example string
string <- "This is a very short sentence. It has only a few words."
library(stringr)
most_common_word <- function(string){
string1 <- str_split(string, pattern = " ")[[1]] # Split the string
string2 <- str_trim(string1) # Remove white space
string3 <- str_replace_all(string2, fixed("."), "") # Remove dot
string4 <- tolower(string3) # Convert to lower case
word_count <- table(string4) # Count the word number
return(names(word_count[which.max(word_count)][1])) # Report the most common word
}
most_common_word(string)
[1] "a"
2
希望這有助於:
most_common_word=function(x){
#Split every word into single words for counting
splitTest=strsplit(x," ")
#Counting words
count=table(splitTest)
#Sorting to select only the highest value, which is the first one
count=count[order(count, decreasing=TRUE)][1]
#Return the desired character.
#By changing this you can choose whether it show the number of times a word repeats
return(names(count))
}
您可以使用return(count)
顯示字,再加上它的重複的次數。當兩個單詞重複相同的次數時,此功能會出現問題,因此請小心。
order
函數獲得最高值(與decreasing=TRUE
一起使用時),則它取決於名稱,它們按字母排序。在'a'
和'b'
這幾個字重複相同的次數的情況下,most_common_word
函數只顯示'a'
。
4
對於一般目的,是更好地使用boundary("word")
在stringr
:
library(stringr)
most_common_word <- function(s){
which.max(table(s %>% str_split(boundary("word"))))
}
sentence <- "This is a very short sentence. It has only a few words: a, a. a"
most_common_word(sentence)
1
使用tidytext
包,以建立解析功能優勢:
library(tidytext)
library(dplyr)
word_count <- function(test_sentence) {
unnest_tokens(data.frame(sentence = test_sentence,
stringsAsFactors = FALSE), word, sentence) %>%
count(word, sort = TRUE)
}
word_count("This is a very short sentence. It has only a few words.")
這給你所有的字計數的表。您可以調整函數以獲得最佳值,但要注意有時候會有首先關係,所以它應該足夠靈活以提取多個獲勝者。
相關問題
- 1. [R編程幫助編寫函數
- 2. 如何編寫一個按順序顯示圖的R函數?
- 3. 編寫一個傳遞數據幀的R函數並返回一個列表
- 4. R中的函數(x):寫一個「函數」而不定義一個函數?
- 5. 在R中編寫函數 - 從庫中調用外部函數
- 6. 編寫一個函數,使用INT或枚舉參數
- 7. 編寫一個名爲spelling_corrector的函數。
- 8. 編寫一個原型函數(C++)
- 9. 幫我編寫一個函數
- 10. 使用'try','raise','except'函數編寫一個短程序
- 11. 使用變量寫一個jQuery函數
- 12. 使用XQuery參數編寫SQL函數
- 13. 寫一個函數用於下列中的R
- 14. 編寫用於處理數據幀的函數R
- 15. 如何編寫一個使用另一個生成10000個值的函數的2個值的函數?
- 16. 一個R函數我data.frame
- 17. 編寫一個函數,該函數的功能
- 18. 在Selenium中編寫一個簡單的函數函數
- 19. 寫一個函數來初始化R/Splus中的參數
- 20. 的R - 填寫一個函數的參數中的省略號
- 21. 使用RxJS編寫函數/操作符
- 22. 使用fopen函數編寫文件
- 23. 編寫全局使用的函數
- 24. 是否可以使用javascript函數只編寫一個可編輯的textarea?
- 25. 編寫一個IDE,使用GCC編譯
- 26. 用JavaScript編寫函數
- 27. 在R中,即時編寫函數(用於sparkTable內容)
- 28. 編寫一個函數來打開一個文件
- 29. 試圖編寫一個使用三個表和AVG()函數的SQL查詢
- 30. R:需要用R中的apply函數編寫相同的代碼
極好的使用'邊界'修飾符。 – www
感謝您的出色答案,它的工作。現在,只是一個問題,如果我有一個文本文件,我讀它作爲desc。 words < - rep('',length(desc)); system.time( 爲(I在1:長度(遞減)){ 字[I] < - most_common_word(降序[I]) } ) 然後,在計算,我對着錯誤。同樣保存這個代碼的問題。 – Shivam
@S。奧利維亞,請參閱有關編輯2?任何建議? – Shivam