我有两个文件: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”应该被替换为空格,但只有“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
最佳答案
这个问题更适合 regex 。可能发生的情况是“我”在 word_list
中,并且自 '
被视为字边界,\bI\b
匹配“I'm”中的“I”。一个简单的解决方法是在 word_list
中将“I'm”放在“I”之前。 。更完整的修复方法是创建一个新的正则表达式,其中撇号不包含在单词边界中。这可以通过用另一个 unicode 字符替换所有撇号来以迂回方式完成。
关于python - 如何使用正则表达式将单词与撇号匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47007253/