【问题标题】:How do I remove everything from a string except what I want?如何从字符串中删除我想要的所有内容?
【发布时间】:2021-07-22 13:12:35
【问题描述】:
好的,所以基本上我希望用户能够输入一些内容,例如"quote python syntax and semantics",删除单词'quote' 和其他任何内容(例如,命令可能是'could you quote for me Python syntax and semantics')然后将其格式化为我可以将它传递给 Wikipedia 文章 URL(在本例中为“https://en.wikipedia.org/wiki/Python_syntax_and_semantics”),请求它并抓取我想要的元素。
任何答案将不胜感激。
【问题讨论】:
标签:
python
parsing
web-scraping
【解决方案1】:
这是一个简单的例子:
import re
msg = input() # Here give as input "quote python syntax and semantics"
repMsg = re.sub("quote", "", msg).strip() # Erase "quote" and space at the start
repMsg = re.sub(" ", "_", repMsg) # Replace spaces with _
print(repMsg) # prints "python_syntax_and_semantics"
python regex module 非常适合做这类事情。请注意,您可能需要微调代码,例如决定何时替换第一次出现与替换全部,此时去除空格等。