2016-04-11 20 views
2

我正在制作一个网页浏览工具,它可以获取游戏服务器上玩家的数量。整数值未知的占位符

目前这样做的最有效的方法是使用请求和BS4,写HTML源到一个txt文件,然后搜索该文件

"/" 

不幸的是我的HTML中包含两个正大幅削减用空格两侧,所以我需要能够像做

“%d /%d”

所以只得到一个与整数,不幸的是我不知道的值两侧,我只需要它只挑一个整数在里面。

prange = list(range(0, 65)) 
searchfile = open("data.txt", "r") 
for line in searchfile: 
    if "/" in line: 

     print (line) 
searchfile.close() 

在此先感谢!

回答

1

你想要的是using regex来搜索文档中的特定模式。

re.search(r'(\d)/(\d)', your_text)将返回所有出现的X/Y,其中XY是1位数字。如果你想要一个以上的数字,你可以take a look at the regex syntax,并写下类似r'(\d+)/(\d+)'

你的榜样,你应该有:

prange = list(range(0, 65)) 
searchfile = open("data.txt", "r") 
for line in searchfile: 
    m = re.search(r'(\d+/\d+)', line) 
    if m: 
     print (line) 
searchfile.close() 
+0

呀数字是两位数的,谢谢你的帮助。不幸的是,我是Python的新手,并将继续研究如何实现您的方法 – Will

1

您可以尝试使用re找到需要的图案:

>>> import re 
>>> re.search('(\d+)\s+/\s+(\d+)', 'dsdsd 111/222 dsdsds').groups() 
('111', '222')