Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:当我使用findall()提取一个数字时,输出是;[&"x27;39772&"x27;];我该如何摆脱“我该怎么做?”;[&"x27;&"x27;];所以我可以转换成浮动?_Python_Floating Point_Format_Findall - Fatal编程技术网

Python:当我使用findall()提取一个数字时,输出是;[&"x27;39772&"x27;];我该如何摆脱“我该怎么做?”;[&"x27;&"x27;];所以我可以转换成浮动?

Python:当我使用findall()提取一个数字时,输出是;[&"x27;39772&"x27;];我该如何摆脱“我该怎么做?”;[&"x27;&"x27;];所以我可以转换成浮动?,python,floating-point,format,findall,Python,Floating Point,Format,Findall,我使用re.findall()从文件中的行中提取一个数字&我可以很好地得到这个数字,但是该函数添加了引号、双引号和方括号,因此我无法将字符串转换为浮点。如何从数字中去掉“[”]”字符以便转换它 这是我的密码: import re count = 0 total = list() hand = open('mbox-short.txt') for line in hand: line = line.rstrip() x = re.findall('New Revision: ([0

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

这是我的密码:

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']
[“['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']"]
回溯(最近一次呼叫最后一次):
文件“revisions.py”,第27行,在
total1=列表(映射(浮动,总计))
ValueError:无法将字符串转换为浮点:['39772']

我试着把数字转换成浮点数,这样我就能计算出平均数。 我错过了什么?在哪里可以找到有关操作输出格式的信息,以便使用它

谢谢大家!

s = "['123']"

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

print(float(s))
# 123.0

只需从字符串中去掉前两个和后两个字符。

使用列表理解将
total
中的所有值转换为float

total=[float(i.split(“”)[1])表示i总计]

不要做
a=str(x)
直接追加
x
它不会让我;我有一个关于元组的错误。