我打开一个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