[英]How add together all numbers from a file separated by a non digit
例如,3.145將是3和145的總和。21,756.54將添加三個數字:21、756和54。假設此文件包含單詞和數字,我將如何獲取這些數字,然后以逗號分隔它們,期,然后將它們加在一起。
這就是我到目前為止
fileName =(input(“輸入要計數的文件名:”))
infile = open(fileName,"r")
for line in infile:
for ch in line:
if ch >= "0":
if ch <= "9":
print(ch, end = "")
所有這一切都為我提供了文件中所有的數字,並且使用了一個長字符串。 我需要將它們用逗號和小數點分開,然后將它們加在一起。 任何幫助將非常感激。
我會用正則表達式和貪婪的+
來拉出所有數字:
import re
with open(fileName,"r") as f:
nums = re.findall("[0-9]+", f.read())
sum(map(int,nums))
您將要在這里使用正則表達式。 在正則表達式中\\d
代表所有數字。 因此,以下將所有數字分成一個列表,然后您可以sum
:
import re
with open(fileName,"r") as f:
list_of_numbers = re.split(r'[^\d]',f.read())
answer = sum(map(int,list_of_numbers))
#answer is now the sum of those integers
表達式[^\\d]
可以解釋如下:
[^...]
表示除 ...提供的字符外的所有字符,因此[^\\d]
表示每個非數字字符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.