![](/img/trans.png)
[英]Trying to extract numbers from a .txt document and sum it using regular expressions in python2.7
[英]How to extract string (numbers) from txt file and convert to integers using regular expressions in python
通讀並解析帶有文本和數字的文件。 提取文件中的所有數字並計算數字的總和。 附上txt文件
這適用於 python 3 及更高版本。
import re
names=open("regex_sum_319771_actual.txt")
numlist = list()
for files in names:
files = files.rstrip()
ext =re.findall('([0-9]+)',files)
if len(ext)!= 1 :
continue
num = int(ext[0])
numlist.append(num)
print('done',sum(numlist))
#the sum should give me an output ending with 689
那可行:
import re
with open("regex_sum_319771_actual.txt", "r") as f:
nums = re.findall(r'([0-9]+)', f.read())
print(sum([int(i) for i in nums]))
PS :如果你不使用with
語句,不要忘記在閱讀后關閉你的文件
您可以逐個字符地迭代字符。
import re
names = open("regex_sum_319771_actual.txt", 'r')
nbr = []
for line in names:
for carac in line:
if re.match(r'\d', carac):
nbr.append(int(carac))
print(sum(nbr))
names.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.