python - 删除字符串中每个句子中特定符号后的单词
问题描述
- 例如,这是字符串:'我有一个苹果。我想吃它。但它是如此疼痛。我想把它转换成这个:'我有一个苹果想吃,它好痛'
解决方案
这是一种无需正则表达式的方法,使用del
您提到的方法:
def remove_after_sym(s, sym):
# Find first word
first = s.strip().split(' ')[0]
# Split the string using the symbol
l = []
s = s.strip().split(sym)
# Split words by space in each sentence
for a in s:
x = a.strip().split(' ')
del x[0]
l.append(x)
# Join words in each sentence
for i in range(len(l)):
l[i] = ' '.join(l[i])
# Combine sentences
final = first + ' ' + ' '.join(l)
final = final.strip() + '.'
return final
在这里,sym 是一个str
(单个字符)。
另外,我在您的示例中非常自由地使用了“句子”一词,sym
它是一个点。但是这里的句子真的意味着字符串的一部分被你想要的符号打破。
这是它的输出。
In [1]: remove_after_sym(string, '.')
Out[1]: 'I have an apple want to eat it it is so sore.'
推荐阅读
- django - 如何组织 Django API
- function - 如何在 sympy 中定义自定义函数?
- api - 币安价格历史精确到秒
- python - 您可以将标准偏差添加到 seaborn regplot 中的点吗?
- python - 如何查看两个 python conda 环境之间的所有差异?
- swiftui - isMomentary 上 SegmentedPickerStyle Swiftui
- reactjs - npm 运行构建错误 - 无法读取未定义的属性“toLowerCase”
- django-rest-framework - 我们可以在不使用 django 中的媒体文件夹来存储动态创建的 .docx 文件的情况下创建任何文件夹/目录吗
- selenium - 同时使用 Selenium 运行多个 Chromedriver 浏览器窗口:需要多少 vCPU 和多少 GB RAM?
- javascript - 如何从 Node.js 服务器向客户端发送结合随机数的图像