2014-12-04 28 views
0

我有一組停用詞,我希望從我解析的內容中刪除。該清單非常詳盡,包含很多代詞和其他常用詞,例如was,being,our等,但不幸的是還有i,a,just和其他。替換給定集合中所有出現的單詞,但前提是該單詞不包含在另一個單詞中

我希望刪除所有這些停用詞,但是只有(如果它們被空格(包括製表符和換行符)包圍)。

我在想在這裏需要一個正則表達式,但它有可能有一個正則表達式裏面有一個變量嗎?

正如我在做這在Python,我會是這樣的:

for word in stopwords: 
    text = text.replace(`regex for current word`, '') 

這是可行的?在這種情況下,正則表達式會是什麼?

回答

0

我最終意識到正則表達式對於我想要做的事情是過度的,因爲我通常只有一個wh itespace身邊的話,我想刪除

最後,我只是去爲這個:

for word in commonWords : 
    text = text.replace(' '+word+' ', ' ') 
+1

如果「單詞」處於開始或結束狀態,這將不起作用。 – vks 2014-12-04 14:08:49

+0

確實如此,但'word'通常是這樣的,它不在文檔的開始或結尾,例如'Disclaimer','Copyright','owner'等。換句話說,我發現它是一個可接受的交易-off。 – user991710 2014-12-04 14:30:59

0

你可以用這個詞\b兩者之間:在docs\b

>>> import re 
>>> txt = "this is a test and retest" 
>>> re.sub(r'\btest\b', '****', txt) 
'this is a **** and retest' 

爲:

匹配空字符串,但只在一個單詞的開頭或結尾... 。這意味着r'\bfoo\b'匹配'foo','foo.','(foo)', 'bar foo baz'但不是'foobar''foo3'

+0

這也將取代'.word.' – vks 2014-12-04 13:04:05

0
(?:^|\s)your_word(?:\s|$) 

這應該you.Use與re.sub去做它。

re.sub(r"(?:^|\s)word(?:\s|$)","",word) 
+0

這項工作,但我似乎無法能夠實際上用給定的單詞替換「單詞」。例如:'for word在commonWords:''regex =「(?:^ | \ s)%s(?:\ s | $)」%word'''''''' re.IGNORECASE)似乎不起作用。 – user991710 2014-12-04 13:26:57

+0

@ user991710創建一個新列表並將re.sub附加到它上面。循環結束後,您將得到結果 – vks 2014-12-04 13:28:11

0

,你可以這樣做:無正則表達式:

[ x for x in "hello how are you".split() if x not in stop_words ] 

STOP_WORDS將是你停用詞列表

看看NLTK:

>>> import nltk 
>>> from nltk.corpus import stopwords 
>>> stop = stopwords.words('english') 
>>> text = "hello how are you, I am fine" 
>>> words = nltk.word_tokenize(text) 
>>> words 
['hello', 'how', 'are', 'you', ',', 'I', 'am', 'fine'] 
>>> [x for x in words if x not in stop] 
['hello', ',', 'I', 'fine'] 
>>> " ".join([x for x in words if x not in stop]) 
'hello , I fine' 
+0

不幸的是,我將不得不再次加入字符串。我試圖避免這樣做,因爲字符串非常大(整個網站的內容)。 – user991710 2014-12-04 13:14:24

+0

@ user991710使用加入你可以加入它 – Hackaholic 2014-12-04 13:17:11

+0

我意識到,我說我想避免必須在至少有幾千個字符的字符串上連接數十次。 – user991710 2014-12-04 13:20:27

相關問題