我打開一個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'
請解釋您的意思是「沒有工作」。它提出了一個錯誤還是隻是不給你想要的結果?如果發生錯誤,請編輯您的帖子以包含完整的回溯。 – SethMMorton
此外,請澄清你想要多一點。例如,'mystr'從哪裏來?我沒有在你的代碼中看到它。 – SethMMorton
對不起,我希望我澄清@SethMMorton – user2371027