簡體   English   中英

如何從 txt 文件中提取字符串(數字)並使用 python 中的正則表達式轉換為整數

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM