在Python中从字符串中去除所有冠词、连接词等
我有一个包含很多句子的列表。我想要遍历这个列表,把所有句子中的一些词去掉,比如“和”、“这个”、“一个”、“是”等等。
我试过这样做:
def removearticles(text):
articles = {'a': '', 'an':'', 'and':'', 'the':''}
for i, j in articles.iteritems():
text = text.replace(i, j)
return text
不过你可能会发现,这样做会把“a”和“an”从单词中间也去掉。我只想在这些词是独立的、被空格分开的情况下去掉,而不是在单词里面去掉。请问有什么更有效的方法吗?
5 个回答
1
def removearticles(text):
articles = {'a': '', 'an':'', 'and':'', 'the':''}
rest = []
for word in text.split():
if word not in articles:
rest.append(word)
return ' '.join(rest)
字典的 in
操作比列表要快。
4
这看起来更像是自然语言处理(NLP)的工作,而不是单纯用正则表达式(regex)能解决的。我建议你看看NLTK(http://www.nltk.org/),我记得它里面有很多像你想去掉的那些填充词的语料库。
9
我建议使用正则表达式,像这样:
def removearticles(text):
re.sub('(\s+)(a|an|and|the)(\s+)', '\1\3', text)
如果你还想去掉开头的空格,可以使用:
def removearticles(text):
re.sub('\s+(a|an|and|the)(\s+)', '\2', text)