[英]How to extract string (numbers) from txt file and convert to integers using regular expressions in python
read through and parse a file with text and numbers.通读并解析带有文本和数字的文件。 extract all the numbers in the file and compute the sum of the numbers.提取文件中的所有数字并计算数字的总和。 txt file attached附上txt文件
This is for python 3 and above.这适用于 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
that will work:那可行:
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 : do not forget to close your file after reading if you do not use with
statement PS :如果你不使用with
语句,不要忘记在阅读后关闭你的文件
You can iterate char by char.您可以逐个字符地迭代字符。
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.