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

标签 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”应该被替换为空格,但只有“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

最佳答案

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

关于python - 如何使用正则表达式将单词与撇号匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47007253/

相关文章:

python - 在 MS VS Code 中重命名 Python 代码中的变量

c++ - Ubuntu 10.04 中的 Boost.Python 教程

python - 在 pdfkit 中显示框而不是文本 - Python3

python - 从python列表迭代插入MySQL表

python - Mac OS X El Capitan下如何清理/Library/Python/2.7/site-packages

python - 如何从 Windows API 文档中使用的接口(interface)名称获取 COM 类的 GUID?

Python 扭曲 react 器 undefined variable

python - 苹果机 : OSError: [Errno 1] Operation not permitted: '/tmp/pip-XcfgD6

python - 如果我将鼠标悬停在坐标区域上,如何更改图标鼠标指针

python - Linux 目录校验和