python - 如果它包含python中的某些字符,如何删除完整的单词
问题描述
如果单词开始或包含某些字符,我想删除句子中的单词。
前任:
string_s = '( active parts ) acetylene cas89343-06-6'
如果单词包含或以 cas 开头,则从字符串中删除整个单词
input1 = '( active parts ) acetylene cas89343-06-6'
output1 = '( active parts ) acetylene'
input2 = '( active parts ) acetylene th.cas1345'
output2 = '( active parts ) acetylene'
解决方案
re.sub
与 pattern 一起使用\b[\w-]*cas[\w-]*\b
,并用一个空格替换,然后修剪输出:
string_s = '( active parts ) acetylene cas89343-06-6'
output = re.sub(r'\b[\w-]*cas[\w-]*\b', ' ', string_s).strip()
print(string_s + '\n' + output)
这打印:
( active parts ) acetylene cas89343-06-6
( active parts ) acetylene
推荐阅读
- python - 试图将类的实例传递给另一个文件
- jquery - 我可以将反应组件存储到状态吗?所以我可以动态加载它
- pandas - 在 Colab 中使用 Ludwig 试图弄清楚如何创建内联的 model_definition.yaml 文件以用于构建模型
- reactjs - 在 React 中调用 Props 的正确方法
- reactjs - 使用钩子时等待状态更新
- java - 我在java编程入门中对我的第一个java实验室的理解如何?我的代码是否正确?
- javascript - 正则表达式意外结果
- python - 用 Python 解析这个 XML 站点地图的最有效方法是什么?
- r - Visual Studio Code 中的自动完成功能:R 中的列名
- html - :在尊重父母的填充之前