Python:在字符串中查找变量
我目前有一些代码可以访问 URL,获取源代码,并且我试图让它从字符串返回一个变量。所以我创建了:
changetime=refreshsource.find('VARIABLE pm NST')
但是它不会在字符串中找到该区域,因为该单词不是VARIABLE,而是其他东西。我如何从该字符串中检索不断变化的变量?
I currently have some code that goes to a URL, fetches the source code, and I'm trying to get it to return a variable from the string. So I created:
changetime = refreshsource.find('VARIABLE pm NST')
But it wouldn't find the area in the string because the word is not VARIABLE, it is something else. How would I retrieve the constantly changing VARIABLE from that string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正则表达式将能够为您实现这一目标。我想你举一些例子来说明什么变量是我们可以想出的严格表达式。要匹配您上面的内容,请执行以下操作:
编辑:此代码实际上可以工作(与第一次尝试不同:)):
A regular expression will be able to achieve this for you. I'd you give some examples of what variable will be the we could come up with a strict expression. To match what you have above something like the following will do:
Edit: this code will actually work (unlike that first attempt :) ):
如果模式真的那么简单,那么这似乎是一个典型的情况,其中 正则表达式 非常有用方便。
注意:如果您不熟悉正则表达式,您可能需要使用一些介绍,例如 http://www.regular -表达式.info。
另一方面,如果模式更复杂,那么您可能需要使用 HTML 解析器,例如 美丽的汤。
If the pattern is really that simple, then this seems a typical case where regular expressions comes quite handy.
Note: if you are new to regular expressions, you may want to use some introduction, like the http://www.regular-expressions.info.
On the other hand, if the pattern is more complex, then you may want to use an HTML parser, like for instance BeautifulSoup.