python - 如何在不使用 REGEX 的情况下删除具有特定模式的字符串?
问题描述
我在处理这些输入和输出时遇到了困难:
input: so sh [/] she had a [^ wheee] .
output: so sh [/] she had a .
input: aah [!] [^ makes sound effects] .
output: aah.
input: and she say (.) I got it [^ repeats 2 times] .
output: and she say (.) I got it .
input: oh no[x 3] .
output: oh no.
input: xxx [^ /bosolasafiso/]
output: xxx
input: hi [* med]
oupt: hi [* med]
我使用了 REGEX 但没有用,我需要确切的条件来满足所有这些条件,并且应该返回结果输出。
所有的“输入”都是从文件中读取的,所以请注意,即使我使用“split()”,像 [^ whee] 这样的词也会被视为两个不同的词。
[/] [*
我需要一个条件,只保留包含的单词 。其他以“[”开头的单词应替换为空字符串。
解决方案
以下解决方案有效,假设您的原始文本中没有大括号。否则,请使用其他一些分隔符对(例如,<<
和>>
)。
s1 = 'so sh [/] [* med] she had a [^ wheee] .'
首先,将每个or片段中的and分别替换为 和 ,以防止它们被消除[
。然后消除方括号中的所有幸存片段。最后,将所有花括号替换回方括号:]
[/ X]
[* X]
{
}
re.sub(r"\[[^]]*]", "", # Remove [Y] blocks
re.sub(r"\[([/*][^]]*)]", r"{\1}", s1)) # Rename [X] to {X}\
.replace("{", "[") # Restore the original brackets\
.replace("}", "]")
#'so sh [/] [* med] she had a .'
推荐阅读
- r - ggplot2:仅在图例中使用颜色(绘图没有符号)
- events - 如何删除 vSphere Client“事件”选项卡上的条目?
- php - 如何从数组更改日期格式
- visual-studio-2015 - TFS 签入被拒绝在哪里可以找到我的待定更改中的文件的映射
- bash - 无参数调用时退出代码
- pouchdb - PouchDB 同步性能
- sql - 在 SQL 中实现 qcut 以创建新列
- c# - Error HRESULT E_FAIL has been returned from a call to a COM component Error while using Shell32
- ruby-on-rails - 由于使用 let 的一些问题,我的一项测试失败了!在 rspec
- go - 为什么 Gorm 在 CreateTable 时忽略一个结构?