-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中Z分數的函數?
- 2. [R編程幫助編寫函數
- 3. R寫函數生成一個新列
- 4. 如何編寫一個按順序顯示圖的R函數?
- 5. 編寫一個傳遞數據幀的R函數並返回一個列表
- 6. R中的函數(x):寫一個「函數」而不定義一個函數?
- 7. 在R中編寫函數 - 從庫中調用外部函數
- 8. 如何編寫一個函數用它的參數調用一個函數?
- 9. 編寫一個函數,使用INT或枚舉參數
- 10. 如何編寫一個返回另一個函數的函數?
- 11. R:如何使用'translate'函數的輸出來編寫表格?
- 12. 編寫返回另一個函數
- 13. 編寫一個返回函數=> T
- 14. 如何在C編寫一個函數
- 15. 編寫一個置換函數
- 16. 編寫一個純sql函數
- 17. 編寫一個原型函數(C++)
- 18. 幫我編寫一個函數
- 19. 編寫一個名爲spelling_corrector的函數。
- 20. 如何編寫一個函數在Python
- 21. 使用ggplot2編寫一個簡單的函數
- 22. 使用'try','raise','except'函數編寫一個短程序
- 23. 使用現有的功能編寫一個函數
- 24. 使用Parsec編寫一個新函數「parse :: String - > Stm」
- 25. 使用變量寫一個jQuery函數
- 26. R,編碼一個函數內的不連續/間隔函數
- 27. 使用XQuery參數編寫SQL函數
- 28. 編寫用於處理數據幀的函數R
- 29. R函數使用字符向量動態生成另一個R函數
- 30. 如何編寫一個使用另一個生成10000個值的函數的2個值的函數?
極好的使用'邊界'修飾符。 – www
感謝您的出色答案,它的工作。現在,只是一個問題,如果我有一個文本文件,我讀它作爲desc。 words < - rep('',length(desc)); system.time( 爲(I在1:長度(遞減)){ 字[I] < - most_common_word(降序[I]) } ) 然後,在計算,我對着錯誤。同樣保存這個代碼的問題。 – Shivam
@S。奧利維亞,請參閱有關編輯2?任何建議? – Shivam