【问题标题】:Python search for hyphenated words with re.searchPython 使用 re.search 搜索带连字符的单词
【发布时间】:2021-07-25 15:11:40
【问题描述】:

我正在尝试使用 PyPDF 在 PDF 中进行搜索,并返回使用 re.search 找到搜索词的页码。但是,当单词中有连字符时,它不起作用。例如,搜索“abc-123”不会返回任何内容。我尝试了下面的代码,它适用于搜索“123”或“abc”,但不会返回“abc-123”。下面是我的代码,来自this thread

# Open the pdf file
pdfFileObj = open('example.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
    
String = 'abc-123'

# Extract text and do the search
for i in range(0, NumPages):
    PageObj = pdfReader.getPage(i)
    Text = PageObj.extractText()
    if re.search(String,Text):
        print("Pattern Found on Page: " + str(i))
        pdfFileObj.close()

感谢任何帮助。提前致谢!

【问题讨论】:

  • 当您期待匹配时,文本中的内容是什么?如果你用 Python repr 测试它,你会发现它有效:re.search('abc-123', 'cat+abc-123+dog')
  • 可能 PDF 中的“-”是图形连字符而不是 ASCII 代码 45 (-)。尝试搜索“abc.123”
  • jarmod - 文本是 PDF 文档页面中的文本(它主要是文本 (ASCII) 文档)。例如,文档中有一行是“ABC-02177 和 ABC-01893”,当我搜索“ABC-01893”时,它没有返回命中。 JasonM1 - 如果我使用任何 pdf 查看器(sumatra,acorbat)搜索“abc-123”,它会找到它,但上面的代码没有。
  • 嘿 JasonM1,我认为它可能是连字符。但是“abc.123”不起作用。,我如何在搜索行中使用re.DOTALL?

标签: python python-re pypdf


【解决方案1】:

re.search 在给定字符串中查找模式。假设文档作为字符串集合或换行符返回意味着它不会搜索第一行。试试findall,然后参加第一场比赛。

...
matches = re.findall(String,Text)
if len(matches) > 0:
    print('Found a match ...')
else:
    print('No match found.')
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 2015-01-20
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多