2014-02-20 18 views
2

比方說,我有以下字符串:沒有空格和特殊字符的字符串中的詞頻?

"hello&^uevfehello!`.<hellohow*howdhAreyou" 

我怎麼會去計算的是它的子英語單詞的頻率是多少?在這種情況下,我希望的結果,例如:

{'hello': 3, 'how': 2, 'are': 1, 'you': 1} 

我搜遍這是類似於此之前的問題,但我真的不能找到任何工作。密切的解決方案似乎使用正則表達式,但它也不起作用。這可能是因爲我錯誤地實現它,因爲我不熟悉它是如何工作的。

How to find the count of a word in a string? 這是最後的答案

from collections import * 
import re 

Counter(re.findall(r"[\w']+", text.lower())) 

我也試着創造一個非常壞的作用,通過串在連續的字母每一個可能的安排迭代(最多8個字母左右最大值)。有這樣做的問題是

1)它的方式長於應該和

2)它增加了多餘的話。例如:如果「hello」在字符串中,「hell」也會被找到。

我不是很熟悉正則表達式,這可能是正確的做法。

+0

要計算英文單詞的頻率,這是不夠的。你將不得不使用類似[ntlk](http://www.ntlk.org)的東西,即使如此,它也會很難,因爲你沒有詞的分隔符。 – msvalkon

+0

你有識別英文單詞的功能或字典嗎? –

+0

我有一個英文單詞列表,我正在比較部分字符串,但它並沒有真正幫助很多。 – Howcan

回答

2
d, w = "hello&^uevfehello!`.<hellohow*howdhAreyou", ["hello","how","are","you"] 
import re, collections 
pattern = re.compile("|".join(w), flags = re.IGNORECASE) 
print collections.Counter(pattern.findall(d)) 

輸出

Counter({'hello': 3, 'how': 2, 'you': 1, 'Are': 1}) 
+0

這是O(len(d))對不對? –

+0

@JayanthKoushik RegExs內部使用狀態機,我相信。所以,我不太清楚複雜性。:( – thefourtheye

+0

你使用的已知單詞列表進行比較(w),所以技術上我不得不使用英語單詞列表? – Howcan

0
from collections import defaultdict 

s = 'hello&^uevfehello!`.<hellohow*howdhAreyou' 
word_counts = defaultdict(lambda: 0) 

i = 0 
while i < len(s): 
    j = len(s) 
    while j > i: 
     if is_english_word(s[i:j]): 
      word_counts[s[i:j]] += 1 
      break 
     j -= 1 

    if j == i: 
     i += 1 
    else: 
     i = j 

print word_counts 
+0

這很好,但只適用於很短的字符串。 – Howcan

0

您需要從字符串中提取所有單詞,然後爲每個需要找子,然後檢查單詞是否有任何字符串的是英文單詞。我用從答案漢英詞典中How to check if a word is an English word with Python?

有一些假陽性的結果卻因此您可能需要使用更好的字典或有一個自定義的方法來檢查需要的話。

import re 
import enchant 
from collections import defaultdict 

# Get all substrings in given string. 
def get_substrings(string): 
    for i in range(0, len(string)): 
     for j in range(i, len(string)): 
      yield s[i:j+1] 

text = "hello&^uevfehello!`.<hellohow*howdhAreyou" 

strings = re.split(r"[^\w']+", text.lower()) 

# Use english dictionary to check if a word exists. 
dictionary = enchant.Dict("en_US") 
counts = defaultdict(int) 
for s in strings: 
    for word in get_substrings(s): 
     if (len(word) > 1 and dictionary.check(word)): 
      counts[word] += 1 

print counts 

輸出:

defaultdict({ '是':1, 'OHO':1, '誒':1 'ELL':3, '哦':1, 'lo':3,'ll':3,'yo':1,'how':2,'hare':1,'ho':2, 'ow':2,'hell':3,''你':1,'ha':1,'hello':3,'re':1,'he':3})

+0

但是,這不是所需的輸出,如果它後面跟着一個o等,地獄應該被忽略。一般來說,應該忽略字符串中其他單詞的子字符串的所有單詞。 –

相關問題