简体   繁体   English

如何从 txt 文件中提取字符串(数字)并使用 python 中的正则表达式转换为整数

[英]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.

相关问题 尝试从.txt文档中提取数字并使用python2.7中的正则表达式求和 - Trying to extract numbers from a .txt document and sum it using regular expressions in python2.7 如何使用 Python 和正则表达式从文件中提取文本部分 - How to extract text part from file using Python & Regular Expressions 如何将数字从python中的文件转换为整数 - How to convert numbers to integers from a file in python 使用正则表达式从文本文件中提取字符串 - Using regular expressions to extract string from text file 如何在python中使用正则表达式提取字符串 - How to extract string with regular expressions in python 编写函数以使用正则表达式从字符串中提取整数 - Writing a function to extract integers from strings using regular expressions 如何使用Python正则表达式从字符串中提取多个模式? - How to extract more than one patterns from a string using Python Regular Expressions? 使用正则表达式从 python 字符串中提取数字和/或字符串 - Extract numbers and/or strings from a python string using regular expression 使用 Python 将带有数字的字符串转换为整数列表 - Convert a string with numbers into a list of integers using Python 使用 Python,如何从 PDF 中提取文本和图像 + 从 output txt 文件中提取颜色字符串和数字 - Using Python, how to extract text and images from PDF + color strings and numbers from the output txt file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM