Python将字符串插入字典

我打开一个.txt文件并阅读


.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]的值,但是由于数字无效,它不起作用。


mic = defaultdict(int)


for k,v in mylist2:

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

不工作。并产生typeerror


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'


守着星空守着你
浏览 246回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python