[英]Extract string from HTML String
i want to extract a number from a html string (i usually do not know the number).我想从一个 html 字符串中提取一个数字(我通常不知道这个数字)。
The crucial part looks like this:关键部分如下所示:
<test test="3" test="search_summary_figure WHR WVM">TOTAL : 286</test>
<tagend>
And i want to extract the "286".我想提取“286”。 I want to do something like "start after "L :" and stop before "<". How can i do this ? Thank you very much in advance.
我想做一些类似“在“L:”之后开始并在“<”之前停止的事情。我该怎么做?在此先非常感谢您。
If the string "TOTAL : number" is unique then use a regular expression to first search this substring and then extract the number from it.如果字符串 "TOTAL : number" 是唯一的,则使用正则表达式首先搜索此子字符串,然后从中提取数字。
import re
string = 'test test="3" test="search_summary_figure WHR WVM">TOTAL : 286</test>'
reg__expr = r'TOTAL\s:\s\d+' # TOTAL<whitespace>:<whitespace><number>
# find the substring
result = re.findall(reg__expr, string)
if result:
substring = result[0]
reg__expr = r'\d+' # <number>
result = re.findall(reg__expr, substring)
number = int(result[0])
print(number)
You can test your own regular expressions here https://regex101.com/你可以在这里测试你自己的正则表达式https://regex101.com/
in your view.py document you can try this:在你的 view.py 文件中,你可以试试这个:
import re
my_string="TOTAL : 286"
int(re.search(r'\d+', my_string).group())
286
286
You can try the following like this below:您可以像下面这样尝试以下操作:
line = "TOTAL : 286"
if line.startswith('TOTAL : '):
print(line[8:len(line)])
Output :输出 :
286
You can use string partitioning to extract a "number" string from the whole HTML string like this (assuming HTML code is in html_string variable):您可以使用字符串分区从整个 HTML 字符串中提取“数字”字符串,如下所示(假设 HTML 代码在 html_string 变量中):
num_string=html_string.partition("TOTAL:")[2].partition("<")[0] num_string=html_string.partition("TOTAL:")[2].partition("<")[0]
there you get num_string with the number as a string, then simply convert it to an integer or whatever you want.在那里你得到 num_string 与数字作为字符串,然后简单地将其转换为整数或任何你想要的。 Keep in mind that this will process the first occurence of anything that looks like "TOTAL: anything_goes_here <", so you want to make sure that this pattern is unique.
请记住,这将处理看起来像“TOTAL:anything_goes_here <”的任何第一次出现,因此您要确保此模式是唯一的。
If your HTML String is this:如果您的 HTML 字符串是这样的:
html_string = """<test test="3" test="search_summary_figure WHR WVM">TOTAL : 286</test>
<tagend>"""
Try this:尝试这个:
int(html_string.split("</test>")[0].split(":")[-1].replace(" ", ""))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.