2013-05-31 24 views
-2

我打開一個txt文件和readlines方法蟒蛇修改字符串插入字典

.txt contents = html_log:Bob -1.2 -0.25 4:53 1 0:02 2 1 3 html_log:John 26.6 0.74 36:00 -4 3 25 26 1:57 74 12 16 -1.11 html_log:Bob -1.2 -0.25 4:53 1 0:04 2 1 3 

change = str(textfile) 

pattern2 = re.compile("html_log:(?P<name>[^ ]*)(?: [^\s]+){4} (?P<score>[^ ]*)") 

try: 
    mylist2=sorted(pattern2.findall(change), key=lambda x: float(x[1]), reverse=True) 
except ValueError: 
    mylist2=sorted(pattern2.findall(change), key=lambda x: float('0'), reverse=True) 

產生

mystr = ('Bob', '0:02'), ('John', '3'),('Bob', '0:02') 

我想要做的是找出是否值不是一個有效的int即。 0:02,如果它不爲0

我想要有一個結果替換:

('Bob', '0'), ('John', '3') 

我試圖把[k]和[V]成我的字典,並添加[v]的值,但它不工作,因爲invaild數字。

mic = defaultdict(int) 

for k,v in mylist2: 
    mic[k] += re.sub(' ^\d*:\d*','0',v) 

沒有工作。併產生類型錯誤

Traceback (most recent call last): 
    File "C:/Python26/myfile.py", line 44, in <module> 
    mic[k] += re.sub(' ^\d*:\d*','0',v) 
TypeError: unsupported operand type(s) for +=: 'int' and 'str' 
+0

請解釋您的意思是「沒有工作」。它提出了一個錯誤還是隻是不給你想要的結果?如果發生錯誤,請編輯您的帖子以包含完整的回溯。 – SethMMorton

+0

此外,請澄清你想要多一點。例如,'mystr'從哪裏來?我沒有在你的代碼中看到它。 – SethMMorton

+0

對不起,我希望我澄清@SethMMorton – user2371027

回答

2

您可以使用try...except條款淘汰非整數:

mic[k] += makeInt(v) 

def makeInt(val, default=0): 
    try: 
     return int(val) 
    except ValueError: 
     return default 

然後你可以用下面的代碼替換該行mic[k] += re.sub(' ^\d*:\d*','0',v)編輯:如果您想使用0以外的值替換非整數,只需將其添加爲其他值r參數:

mic[k] += makeInt(v, 1) 
+0

我可以使除非更改爲非整數@ASGM – user2371027

+0

@ user2371027你當然可以!只要將'return 0'改爲'return 1',就可以讓它返回任何你想要的值。 – ASGM

+0

@ user2371027我已經調整了函數,使默認的非整數值爲0,但是您可以傳遞一個不同的默認值作爲參數。希望有所幫助。 – ASGM