簡體   English   中英

Python:當我使用 findall() 提取數字時,output 是“['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() 從文件中的行中提取數字,我可以很好地獲取數字,但是 function 添加了引號、雙引號和方括號,因此我無法將字符串轉換為浮點數。 如何從數字中去除“['']”字符以便進行轉換?

這是我的代碼:

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)

output:

["['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']

鏈接到文件“mbox-short.txt”

我正在嘗試將數字轉換為浮點數,以便計算平均值。 我錯過了什么? 我在哪里可以找到有關處理 output 格式的信息以便我可以使用它?

謝謝!

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM