函数打印值,但返回“None”

2024-10-01 02:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

def findLineParam(sprotParam, pos):

    if line[:2] == sprotParam:
        start = pos
        while line[start] == " ":
            start += 1
        stop = start + 1 
        while stop < len(line) and not line[stop] in (" ", ";"):
            stop += 1
        print(line[start:stop]) # prints the correct value!
        return line[start:stop] # returns None? 

简要说明代码的功能是,它应该输入一个字符串(关键字),例如“ID”,并在文本文件的一行中找到它,然后它应该在空白读取到下一个“”或“;”后找到第一个值并返回这个值。我可以看到,当我打印行时,它返回的正是我想要的,但当我返回它时,它返回“无”。你知道吗

每当我将“sprotParam”改为一个输入列表(*sprotParam)时,它会返回值,但也会返回与文件中的行相对应的相等数量的“None”,我相信这表明它会在所有行上迭代并执行操作,而这是不应该的

调用函数的代码

try:
    file = input("Enter filename: ")
except IOError as e:
    print("That is not a recognised filename. Error given: " + str(e)) 
    sys.exit(1) # Close the program

with open(file, 'r') as infile:
    for line in infile:
        ident = findLineParam("ID", 2)

Tags: the代码inposnoneidlinenot
3条回答

如果函数必须返回某个值,则应返回一个默认值(仅在if语句中返回,因此如果不匹配此if,则不返回任何值) 我知道这不能解决你的问题,但最好是得到这个

line不在函数的作用域内,因此需要将其作为参数传递给函数:

def findLineParam(sprotParam, pos, line):
    if line[:2] == sprotParam:
        start = pos
        while line[start] == " ":
            start += 1
        stop = start + 1 
        while stop < len(line) and not line[stop] in (" ", ";"):
            stop += 1
        print(line[start:stop]) # prints the correct value!
        return line[start:stop] # returns None? 

with open(file, 'r') as infile:
    for line in infile:
        ident = findLineParam("ID", 2, line)

更新

以下是代码的简化版本:

def findLineParam(sprotParam, file):
    for line in file.split(sprotParam):#split by parameter
        if line != '<':
            for item in line.split(): #split by whitespace
                if item != '=':
                    print(item)
                    return item

    raise Exception(f'No {sprotParam} parameters were found in the given file')

file = 'test.txt'
with open(file, 'r') as f:
    ident = findLineParam("ID", f.read())

现在,如果您为test.txt运行此命令:

<ID= 'foo'    > <div></div>
asdfnewnaf

它将返回'foo'。你知道吗

正如@NoxFly所暗示的,所有路径都不会返回。你知道吗

def findLineParam(sprotParam, pos, line):
    ret = ''
    if line[:2] == sprotParam:
        start = pos
        while line[start] == " ":
            start += 1
        stop = start + 1 
        while stop < len(line) and not line[stop] in (" ", ";"):
            stop += 1
        print(line[start:stop]) # prints the correct value!
        ret = line[start:stop] # returns None? 
   return ret

with open(file, 'r') as infile:
    for line in infile:
        ident = findLineParam("ID", 2, line)

更好的方法是使用regex而不是while循环。 例如,正则表达式将找到值。你知道吗

r"ID:([^(\s|;)]*)"

相关问题 更多 >