Python:在字符串中查找变量

发布于 2024-12-07 16:29:58 字数 180 浏览 0 评论 0原文

我目前有一些代码可以访问 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌上芳菲 2024-12-14 16:29:58

正则表达式将能够为您实现这一目标。我想你举一些例子来说明什么变量是我们可以想出的严格表达式。要匹配您上面的内容,请执行以下操作:

import re
# this will match 01:23, 11:34, 12:00, etc.
timex = re.compile('.*(\d{2}:\d{2})[ ]?pm NST')
match = timex.match(text, re.M|re.S)
variable = match.groups(0)

编辑:此代码实际上可以工作(与第一次尝试不同:)):

import re
# this will match 01:23, 11:34, 12:00, etc.
timex = re.compile('(\d{2}:\d{2})[ ]?pm NST')

match = timex.search(text)
if match:
    variable = match.groups(0)

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:

import re
# this will match 01:23, 11:34, 12:00, etc.
timex = re.compile('.*(\d{2}:\d{2})[ ]?pm NST')
match = timex.match(text, re.M|re.S)
variable = match.groups(0)

Edit: this code will actually work (unlike that first attempt :) ):

import re
# this will match 01:23, 11:34, 12:00, etc.
timex = re.compile('(\d{2}:\d{2})[ ]?pm NST')

match = timex.search(text)
if match:
    variable = match.groups(0)
没有你我更好 2024-12-14 16:29:58

如果模式真的那么简单,那么这似乎是一个典型的情况,其中 正则表达式 非常有用方便。
注意:如果您不熟悉正则表达式,您可能需要使用一些介绍,例如 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文