【问题标题】:Dictionary and regex match objects for building a URL用于构建 URL 的字典和正则表达式匹配对象
【发布时间】:2020-06-07 02:14:58
【问题描述】:

试图从此处的 pdf 数据中预填充表单,但我遇到了一些正则表达式匹配对象和字典。

“缩写”代码:

import PyPDF2, regex, urllib.parse, webbrowser
#using regex instead of re as I was nesting lookarounds, but might not need to do this anymore.

### Define the field ids with sensible names

entering_email = 'field45865550'
uid_number = 'field45865570'
fname = 'field45865574-first'
lname = 'field45865574-last'
add_1 = 'field45865578-address'
city = 'field45865578-city'
state = 'field45865578-state'
zip = 'field45865578-zip'

跳过 Py2PDF 部分,因为这看起来不错。请原谅我的命名约定。

### Open text file, search for field contents, and define them
with open (pdffile+'-text.txt', 'r') as text_file:
    text = text_file.read() 
    entering_email_value = regex.search(r'(?<=Email:\|)(.*?)(?=\|)(?=.*\|Manager Information:)', text) or ["---"]
    uid_number_value = regex.search(r'(?<=UID Number:\|)(.*?)(?=\|)', text) or ["---"]
    fname_value = regex.search(r'(?<=First Name:\|)(.*?)(?=\|)', text) or ["---"]
    lname_value = regex.search(r'(?<=Last Name:\|)(.*?)(?=\|)', text) or ["---"]
    add_1_value = regex.search(r'(?<=Last Name:\|.*)(?<=Address:\|)(.*?)(?=\|)(?=.*Employee Information:)', text) or ["---"]
    city_value = regex.search(r'(?<=Last Name:\|.*)(?<=City & State:\|)(.*?)(?=,)(?=.*Employee Information:)', text) or ["---"]
    state_value = regex.search(r'(?<=Last Name:\|.*)(?<=, )(.*?)(?= )(?=.*Employee Information:)', text) or ["---"]
    zip_value = regex.search(r'(?<=Last Name:\|.*)(?<=[A-Z][A-Z] )(.*?)(?=\|)(?=.*Employee Information:)', text) or ["---"]

getVars = {entering_email: entering_email_value.group(), 
            uid_number: uid_number_value.group(),
            email: email_value.group(),
            fname: iw_fname_value.group(),
            lname: iw_lname_value.group(),
            city: city_value.group(),
            state: state_value.group(),
            zip: zip_value.group()
            }

webbrowser.open(url + urllib.parse.urlencode(getVars), new=0, autoraise=True)

正则表达式语法可能看起来很奇怪,但工作正常 - 我将“\n”替换为“|”因为我不知道 DOTALL 标志。我的问题是看起来附加到 regex.searches 的 OR 语句被忽略了。源文件会定期丢失信息,所以默认用“”或“---”填充它,没有匹配是我想要做的。我目前正在研究列表推导来做到这一点。

基本上,我的问题是我这样做是“正确的”吗?我敢肯定这是hacky。

我的另一个问题是我现在想要解决的问题,列表理解是用 "" 替换 none 的正确答案吗? - 以及对结构和语法的任何帮助 - 似乎 我应该能够将其放入字典声明中?

【问题讨论】:

  • 请尽可能清楚地解释您的问题。它还有助于提出具体问题。
  • 你为什么要逃跑 | ?你的正则表达式对我来说看起来很奇怪。我不确定他们做的正是你想让他们做的事情。
  • 例如,随机取一个 (?=\|) 表示您希望在此之前的文本在此之后匹配.. 而这将匹配的是一个 '|'符号。
  • 对不起,我不清楚 - 我认为 OR 语句被忽略了,因为当没有匹配时,它会抛出异常错误“'list' object has no attribute 'group'” - I '希望能够只分配“”或“”。
  • 我要逃跑了 |因为我用 | 替换了 \n在我知道使用 DOTALL 标志之前 - 所以它现在有点像分隔符。这里有一个巨大的学习曲线。

标签: python regex dictionary object match


【解决方案1】:

当然这已经回答过了:

return string with first match Regex

看起来这只是通过添加“|$”在我的语句中嵌入''默认值的问题

【讨论】:

    猜你喜欢
    • 2012-06-21
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多