2014-12-04 27 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

相关问题