我知道這個問題可能看起來并不難,但它是一個棘手的問題,讓我解釋一下。
輸入
Bla bla this is 45 text 10.5 bla bla -1 這很棘手
輸出
54.5
解釋
45 10.5 -1 = 54.5
我已經可以對字串中的數字或數字求和,但我不知道如何區分浮點數和負數,如 10.5 和 -1。下面是我現在的代碼,它只對整數求和,而不是浮點數或負數:
def findSum(text):
string = "0"
Sum = 0
for char in text:
if (char.isnumeric()) :
string = char
nums = char.split('.')
else:
Sum = float(string)
string = "0"
return Sum float(string)
text = "sqdkl 45 qsd 10.5 qsdaf -1"
print(findSum(text))
也沒有進口
uj5u.com熱心網友回復:
使用正則運算式:
import re
inpt = "Bla bla this is 45 text 10.5 bla bla -1 this is tricky"
result = 0
matches = re.findall("[-]*[0-9.] ", inpt)
for match in matches:
result = float(match)
result # 54.5
uj5u.com熱心網友回復:
檢查每個“單詞”是正數還是負數并添加到total:
def findSum(text):
total = 0
for word in text.split():
if word[0]=="-" and word[1:].count(".")<=1 and word[1:].replace(".", "").isnumeric():
total = float(word)
elif word.count(".")<=1 and word.replace(".", "").isnumeric():
total = float(word)
return total
>>> findSum("Bla bla this is 45 text 10.5 bla bla -1 this is tricky")
54.5
或者,嘗試添加每個“單詞”并忽略例外:
def findSum(text):
total = 0
for word in text.split():
try:
total = float(word)
except ValueError:
continue
return total
uj5u.com熱心網友回復:
使用 消除每個字母字符str.replace,拆分字串并轉換為float.
可以使用 獲取字母字串列string.ascii_letters。由于您不能使用匯入,請將其輸出復制粘貼到您的代碼 ( print(string.ascii_letters)) 中。
text = "sqdkl 45 qsd 10.5 qsdaf -1"
import string # it can be removed and introduce an own list
chars_to_be_removed = string.ascii_letters ',:;' # depends on the data
for char in chars_to_be_removed:
text = text.replace(char, '')
sum_ = sum(float(n.strip()) for n in text.split(' ') if n != '')
print(sum_)
編輯:更強的方法
由于沒有給出關于字串中允許的字符、重復.或“-”(是語言和算術運算式的一部分!)的規則,這里是一個更健壯的實作。它基于-build-in 包groupby的功能。itertools它可以處理字串,例如
"sqdkl 45 qsd 10.5 qsd....af -1 bih-ds----a10".
它使用允許的字符集而不是要洗掉的字符集。
import itertools as it
text = "sqdkl 45 qsd 10.5 qsd....af -1 bih-ds----a"
import string # it can be removed and introduce an own list
allowed_chars = string.digits '-.'
sum = 0
for match, chars in it.groupby(text, lambda s: s in allowed_chars):
if match:
num = ''.join(chars)
# group with 1 element
if '.' == num or '-' == num:
continue
# group with more elements
if num.count('-') > 1 or num.count('.') > 1:
continue
#print(num)
sum = float(''.join(num))
print(sum)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445433.html
標籤:Python python-3.x
