如何使用正则表达式将单词与撇号匹配

时间:2017-10-30 02:13:10

标签: python

我有两个文件:text_data和word_list。我正在尝试编写一个函数,从text_data中删除word_list中出现的所有单词。但是,我认为我没有正确地写我的正则表达式。这是我的代码

def remove_stopwords_from_file(text_data, word_list):
file_content = text_data
for word in word_list.split():
    file_content = re.sub(r"\b"+word+r"\b"," ", file_content)
return file_content

这是输出的一部分

opening monologue jerry 'm line supermarket two women   front  one  total   eight dollars three dollars course choose pay use pause   gesture   audience   response audience cheque jerry cheque now fact 's a woman   front      's writing

有些单词被空格取代。但对于有撇号的单词,只有一半的单词被替换。例如,“我是”应该被空白替换,但只有“I”被替换,“'m”仍然存在。

我是python的新手,希望有人能帮我解决这个问题。感谢

word_list

的示例
below
between
both
but
by
can't
cannot
could
couldn't

text_data示例

% Opening monologue

Jerry: So, I'm on line at the supermarket. Two women in front of me. One of

them, her total was eight dollars, the other three dollars. They both

of course choose to pay by the use of the (pause and gesture to audience

2 个答案:

答案 0 :(得分:1)

这将是一个更适合的问题。可能发生的是“我”在word_list,并且由于'被视为字边界,\bI\b与“我是”中的“我”匹配。一个简单的解决方法是在word_list中将“我”放在“我”之前。更完整的修复方法是创建一个新的正则表达式,其中撇号不包含在单词边界中。这可以通过用另一个unicode字符替换所有的撇号来以迂回的方式完成。

答案 1 :(得分:0)

好的,我尝试了类似的东西。告诉我它是否有意义。

档案a.txt with open('a.txt', 'r') as content_file:
    content = content_file.read()

print content
“d sgr sdfxc fbcxvhstdf bc gerdfx'g srdf sdg'ffg d's gfd'g fd \ n”

re.sub(r'gerdfx\'g'," ",content)
“d sgr sdfxc fbcxvhstdf bc srdf sdg'ffg d's gfd'g fd \ n”

它确实用空格代替。

然后我尝试用变量做同样的事 x = "gerdfx'g"
re.sub(r''+x," ",content)
“d sgr sdfxc fbcxvhstdf bc srdf sdg'ffg d's gfd'g fd \ n”

这似乎也有效。你能看一下这个并说出你尝试过不同的东西吗?