正如标题所述,我正在尝试创建(def)一个函数,其中导入 re ,然后解析字符串(使用正则表达式)以将数字添加到列表末尾。我知道代码在我试图保存的函数之外工作。我从来没有创建过如此复杂的函数,所以我不确定缩进的使用或是否可能。
编辑:缩进我的“打印”语句后,该函数确实可以工作。但是它会打印出所有 87 行以及每行的总和。我把它放在循环的外面,这样它就只显示一行。我只想它显示最后一行(总和以及计算了多少行)。之前,在函数之外处理此问题时,我尝试进行拼接,但没有成功。我也只使用 Python 大约 5 天,所以请温柔一点,哈哈。我经常回去查看材料或谷歌寻找我能理解的答案。
#create function to import the re lib and then parse through "fhand" after the file is opened by calling this function.
def Ptfs():
import re
count = 0
total = list()
for line in fhand:
numbers = re.findall('[0-9]+' ,line)
for number in numbers :
num = int(number)
total.append(num)
count = count + 1
print(sum(total), "There were", count, "lines that were summed.")
fhand = open("file_name", 'r')
Ptfs()
您可以进行一些改进
def Ptfs():
import re
count = 0
total = list()
for line in fhand:
numbers = re.findall('[0-9]+' ,line)
for number in numbers :
num = int(number)
total.append(num)
count = count + 1
print(sum(total), "There were", count, "lines that were summed.")
Ptfs("file_name")