Python:使用列表索引作为函数参数

2024-10-04 01:29:58 发布

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

我尝试使用列表索引作为函数的参数,该函数对一些文本文件执行正则表达式搜索和替换。不同的搜索模式被分配给变量,我把变量放在一个列表中,当函数在给定的文本中循环时,我想给它提供一个列表

当我使用列表索引作为参数调用函数时,什么都不会发生(程序会运行,但不会在文本文件中进行替换),但是,我知道代码的其余部分正在工作,因为如果我单独使用任何搜索变量调用函数,它的行为将与预期的一样

当我给print函数提供与我试图调用我的函数相同的列表索引时,它会准确地打印我试图作为函数参数提供的内容,所以我被难住了


search1 = re.compile(r'pattern1')
search2 = re.compile(r'pattern2')
search3 = re.compile(r'pattern3')

searches = ['search1', 'search2', 'search2']
i = 0

for …
  …
  def fun(find)
    …

  fun(searches[i])
  if i <= 2:
    i += 1  
…

如前所述,如果我使用fun(search1),脚本会根据需要编辑文本文件。同样,如果我添加行print(searches[i]),它将打印search1(等等),这就是我试图作为fun的参数给出的

作为Python和编程的新手,我的研究技能有限,但在尽我所能四处探索并随后运行print(searches.index(search1)并得到一个pattern1 is not in list错误后,我的主要(也是唯一)理论是,我给我的函数的是实际的正则表达式,而不是它所存储的变量

非常感谢任何即将到来的帮助


Tags: 函数文本re列表参数模式print调用函数
2条回答

谢谢大家的帮助。eyl327关于我应该使用列表或字典来存储正则表达式的评论为我指明了正确的方向

然而,因为我在搜索模式中使用了regex,所以在我还创建了一个编译表达式列表(通过this thread on stored regex strings发现)之前,我无法让它工作

非常感谢juanpa.arrivillaga的观点,我本应该证明自己是MRE(请原谅,由于技能非常有限,这本身可能很难做到),我只想摘录一段经过稍微修改的实际代码版本来演示答案(再一次,请原谅它的长篇大论,我现在无法做任何更优雅的事情):


…

# put regex search patterns in a list
rawExps = ['search pattern 1', 'search pattern 2', 'search pattern 3']
# create a new list of compiled search patterns 
compiledExps = [regex.compile(expression, regex.V1) for expression in rawExps]

i = 0
storID = 0
newText = ""

for file in filepathList:
    for expression in compiledExps:
        with open(file, 'r') as text:
            thisText = text.read()
            lines = thisThis.splitlines()
            setStorID = regex.search(compiledExps[i], thisText)
            if setStorID is not None:
                storID = int(setStorID.group())
            for line in lines:
                def idSub(find):
                    global storID
                    global newText
                    match = regex.search(find, line)
                    if match is not None:
                        newLine = regex.sub(find, str(storID), line) + "\n"
                        newText = newText + newLine
                        storID = plus1(int(storID), 1)
                    else:
                        newLine = line + "\n"
                        newText = newText + newLine
                # list index number can be used as an argument in the function call
                idSub(compiledExps[i])
            if i <= 2:
                i += 1
        write()
        newText = ""
    i = 0

尝试将searches列表更改为[search1, search2, search3],而不是['search1', 'search2', 'search2'](其中只使用字符串而不使用regex对象)

相关问题 更多 >