逛到一個有意思的博客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
(pattern, repl, string, count=0, flags=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=None, maxsplit=-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()的第一個參數是分隔符,如果什么都不填就是默認是以空格來分隔。
第一種方法需要用到正則表達式,第二種方法則需要有分隔符(我猜是不是這個原因,在原網頁上總答案數的數字后有個空格存在)。 這兩種方法都有點局限性,不知道是否有更好的方法來分離字符串中的數字。