我是一个非常新的编码用户,我写了一个小的python脚本,但有一些格式问题我无法解决,你能不能给出一些建议?
while(True):
keyword = "edit clients are "
p = buf.find(keyword)
if(p == -1):
break
p = buf.find(keyword)
usage_count = int(buf[:p].split())
buf = buf[p+len(keyword):]
print "================== %s usage_count" % usage_count
ret.append(LicenseSitRep(usage_count))
return ret
输出结果显示:
TypeError: int() argument must be a string or a number, not 'list'
我的搜索值低于,我的预期输出应为11.
Jun 14 11:01:58 license server: Current accepted edit clients are 11.
答案 0 :(得分:0)
错误来自此行
usage_count = int(buf[:p].split())
原因是split
函数返回list
而不是str
,您可以更改代码。
usage_count = int(buf[:p].split()[0])
修改强>
要获取11
,您可以从调试过程中找到。
[in] buf = r"Jun 14 11:01:58 license server: Current accepted edit clients are 11."
[in] p = 49
[in] buf[p:]
[out] 'edit clients are 11.'
[in] buf[:p]
[out] 'Jun 14 11:01:58 license server: Current accepted '
[in] buf[p:].split(" ")
['edit', 'clients', 'are', '11.']
[in] buf[p:].split(" ")[-1]
[out] '11.'
[in] buf[p:].split(" ")[-1].split(".")
[out] ['11', '']
[in] buf[p:].split(" ")[-1].split(".")[0]
[out] '11'
你可以试试这段代码。
usage_count = int(buf[p:].split(" ")[-1].split(".")[0])
答案 1 :(得分:0)
为什么不通过re来利用正则表达式而只是这样做?
import re
buf = "Jun 14 11:01:58 license server: Current accepted edit clients are 11."
# ...
p = buf.find(keyword)
buf = buf[p+len(keyword):]
buf = int(re.sub(r'[^\w]', ' ', buf))
usage_count = buf
答案 2 :(得分:0)
使用正则表达式更可行我猜
import re
buf = "Jun 14 11:01:58 license server: Current accepted edit clients are 11."
if bool(re.match(r'.*edit\sclients\sare\s\d+.$', buf)):
usage_count = re.findall(r'edit\sclients\sare\s(\d+?)\.', buf)
print "================== %s usage_count" % usage_count[0]