【问题标题】:python Regular expression [closed]python正则表达式[关闭]
【发布时间】:2015-10-22 06:32:17
【问题描述】:
file = open("demo.txt","r")
text = file.read()

def find(info):
    match = re.findall(r"info+\w+\d+",text)
    if match:
        print(match)
    else:
        print("Not found!")

我的问题是,如何在函数中应用“信息”, 不知道该怎么做。

任何帮助将不胜感激

【问题讨论】:

  • 你能说清楚点吗?该函数采用参数info,但您为findall 函数提供参数text...
  • 很抱歉造成混乱!

标签: python regex function


【解决方案1】:

我想这就是你所追求的:

file = open("demo.txt","r")
text = file.read()

def find(info,text):
    match = re.findall(info + "+\w+\d+",text)
    if match:
        print(match)
    else:
        print("Not found!")

# This is how you call the function
find("whatever info is supposed to be",text)

【讨论】:

  • 这仍然使用re.findall中的全局变量text而不是函数参数info
  • @isosceleswheel:很好发现 - 代码相应调整
  • 非常感谢您的帮助!!
【解决方案2】:

稍微检查一下你的 Python 语法。

# beware "file" is a python keyword so you might want to use a different name
file = open("demo.txt","r")
# your text is called "text" so that is the argument to use in the function call
text = file.read()

# define the function: 

def find(info):
    # your variable is called "info" in the function so call findall on "info"
    match = re.findall(r"info+\w+\d+",info)
    if match:
        print(match)
    else:
        print("Not found!")

# call the function on "text" since that is the name of the local variable you created with file.read()::
find(text)

【讨论】:

    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 2013-10-28
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    相关资源
    最近更新 更多