2016-11-13 83 views
1

找到整型和字符串,我需要拆分此字符串:從拆分句子

"We shall win 100 dollars in the next 2 years" 

,並與整數和字符串([100,2],[We,shall,win,dollars,in,the,next,years])列表返回一個元組。

我嘗試至今:

lst_int =[] 
    lst_str =[] 
    tup_com =(lst_int,lst_str) 
    words = input_string.split() 
    for i in words: 
     if i == int(): 
      lst_int.append(i) 
     elif i != int(): 
      lst_str.append(i) 
    return tup_com 

回答

0

您可以使用多種方法做到這一點:

1)檢查isdigit

sentence = "We shall win 100 dollars in the next 2 years" 

str_list=[] 
int_list=[] 
for word in sentence.split(): 
    if word.isdigit(): 
     int_list.append(int(word)) # cast at the same time 
    else: 
     str_list.append(word) 

問題:如果數字爲負數,你必須檢查包含減號,空格字符的數字,這些數字仍然被認爲是有效的數字,這使isdigit更爲複雜。這可能會導致你的正則表達式,這是比較複雜的,並打開整數潘多拉的盒子使用正則表達式解析...(我甚至不mentionning浮點數)

2)依靠蟒蛇整數解析:

str_list=[] 
int_list=[] 
for word in sentence.split(): 
    try: 
     int_list.append(int(word)) 
    except ValueError: 
     str_list.append(word) 

由於異常處理,速度稍慢一些,但在所有情況下都可以正常工作,甚至可以泛化爲浮點數。

+0

非常感謝你的出色解釋。 Merci beaucoup先生! – Wanderer

0

這可以通過調整你的狀況來實現。 i == int()並不真正做你的想法; int()回報0所以你基本上連續檢查,如果i == 0其中,總是會False(造成的一切附加到lst_str

而是使用str.isdigitfor環路這樣:

if i.isdigit(): 
    lst_int.append(i) 
else: 
    lst_str.append(i) 

str.isdigit檢查您提供的字符串中的字符並評估它們是否都是數字(並且字符串非空)。

然後,tup_com結果爲:

(['100', '2'], ['We', 'shall', 'win', 'dollars', 'in', 'the', 'next', 'years']) 

順便說一句,你不需要tup_com這裏,簡單地返回用逗號分隔的列表和一個元組創建包含他們。

即:

return lst_int, lst_str 
+0

非常感謝你 – Wanderer

1

您可以用簡單的regex做

import re 
s = "We shall win 100 dollars in the next 2 years" 

t = (re.findall("[0-9]+",s),re.findall("[a-zA-Z]+",s)) 
+0

另一個偉大的方法。謝謝! – Wanderer