Python:当我使用 findall() 提取数字时,输出为“['39772']”如何去掉“['']”以便转换为浮点数?

Python: when I extract a number using findall() the output is " [ ' 39772 ' ] " how do I get rid of " [ ' ' ] " so I can convert to float?

我正在使用 re.findall() 从文件中的行中提取一个数字,我可以很好地得到这个数字,但是该函数添加了引号、双引号和方括号,这样我就可以' t 将字符串转换为浮点数。如何去掉数字中的“[ ' ' ]”字符以便进行转换?

这是我的代码:

import re
count = 0
total = list()
hand = open('mbox-short.txt')
for line in hand:
    line = line.rstrip()
    x = re.findall('New Revision: ([0-9.]+)', line)
    if len(x) > 0:
        count += 1
        a = str(x)
        total.append(a)
    
print(total)     # test print

total1 = list(map(float, total))          # line 24 -- where I get the ValueError

print(sum(total1)/count)

输出:

["['39772']", "['39771']", "['39770']", "['39769']", "['39766']", "['39765']", "['39764']", " 
['39763']", "['39762']", "['39761']", "['39760']", "['39759']", "['39758']", "['39757']", " 
['39756']", "['39755']", "['39754']", "['39753']", "['39752']", "['39751']", "['39750']", " 
['39749']", "['39746']", "['39745']", "['39744']", "['39743']", "['39742']"]
Traceback (most recent call last):
  File "revisions.py", line 27, in <module>
    total1 = list(map(float, total))
ValueError: could not convert string to float: ['39772']

link to file 'mbox-short.txt'

我正在尝试将数字转换为浮点数,以便计算平均值。 我错过了什么?我在哪里可以找到有关处理输出格式的信息以便我可以使用它?

谢谢!

s = "['123']"

s = s[2:-2] # remove first 2 and last 2 characters

print(float(s))
# 123.0

只需从字符串中删除第一个和最后两个字符。

使用列表理解将 total 中的所有值转换为浮点数。

total = [float(i.split("'")[1]) for i in total]