Lucystonenix

       逛到一个有意思的博客http://cuiqingcai.com/category/technique/python 在里面看到一篇关于ValueError: invalid literal for int() with base 10错误的解析,针对这个错误,博主已经给出解决办法,使用的是re.sub 方法

1 totalCount = \'100abc\'
2 totalCount = re.sub("\D", "", totalCount)

      但是没有说明什么含义,于是去查了其他的资料,做一下记录:

   在Python3.5.2 官方文档re模块中sub函数的定义是:

   re.sub(patternreplstringcount=0flags=0)

       在字符串 string 中找到匹配正则表达式 pattern 的所有子串,用另一个字符串 repl 进行替换。如果没有找到匹配 pattern 的串,则返回未被修改的 string。Repl 既可以是字符串也可以是一个函数。

      由此可分析上面使用的语句的含义:在\'100abc\'这个字符串中找到非数字的字符(正则表达式中\'\D\'表示非数字),并用""替换,然后返回的就是只剩下数字的字符串。

>>> totalCount = \'100abc\'
>>> totalCount = re.sub("\D", "", totalCount)
>>> print(totalCount)
100
>>> type(totalCount)
<class \'str\'>

  好吧,以上说明完毕,不过其实我想到的是我爬取知乎所关注的问答时,所遇到的类似的问题:

1 answer_num_get = soup.find(\'h3\', {\'id\': \'zh-question-answer-num\'})   # 答案数量:32 个回答
2 if answer_num_get is not None:
3     answer_num = int(answer_num_get.split()[0])
4 n = answer_num // 10

     其中第三行之所以能用int(),是因为string.split()[0]将answer_num_get的值“32 个回答”提取出数字(注:32后面有一个空格,在这里非常重要,因为知乎上抓取回来的这个元素就是)

     split()的定义    str.split(sep=Nonemaxsplit=-1)

>>> import string
>>> a = "32 个答案"
>>> b = a.split()[0]
>>> print(b)
32
>>> type(b)
<class \'str\'>
>>> c = \'1,2,3\'
>>> c.split(\',\')
[\'1\', \'2\', \'3\']
>>> c.split(\',\')[0]
\'1\'
>>> c.split(\',\')[1]
\'2\'
>>> 

由此可看出split()的第一个参数是分隔符,如果什么都不填就是默认是以空格来分隔。

 

第一种方法需要用到正则表达式,第二种方法则需要有分隔符(我猜是不是这个原因,在原网页上总答案数的数字后有个空格存在)。  这两种方法都有点局限性,不知道是否有更好的方法来分离字符串中的数字。

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-12-22
  • 2021-12-22
  • 2021-06-14
  • 2021-11-24
  • 2022-01-06
猜你喜欢
  • 2022-12-23
  • 2022-03-11
  • 2021-07-04
  • 2022-01-01
  • 2022-12-23
相关资源
相似解决方案