Parse PDF files text content for keywords.

    Args:
      path: PDF file path.

    Returns:
      match: set of unique occurrences of every match.
1350
def grepPDF(self, path):
    
    with open(path, 'rb') as pdf_file_obj:
      match = set()
      text = ''
      pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj)
      pages = pdf_reader.numPages
      for page in range(pages):
        page_obj = pdf_reader.getPage(page)
        text += '\n' + page_obj.extractText()
      match.update(set(x.lower() for x in re.findall(
          self._keywords, text, re.IGNORECASE)))
    return match
468396
def read(path, encoding="utf-8"):
    
    with open(path, "rb") as f:
        content = f.read()
        try:
            text = content.decode(encoding)
        except:
            res = chardet.detect(content)
            text = content.decode(res["encoding"])
    return text
1197321
def match(self, path_pattern):
        
        cf = self._flavour.casefold
        path_pattern = cf(path_pattern)
        drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
        if not pat_parts:
            raise ValueError("empty pattern")
        if drv and drv != cf(self._drv):
            return False
        if root and root != cf(self._root):
            return False
        parts = self._cparts
        if drv or root:
            if len(pat_parts) != len(parts):
                return False
            pat_parts = pat_parts[1:]
        elif len(pat_parts) > len(parts):
            return False
        for part, pat in zip(reversed(parts), reversed(pat_parts)):
            if not fnmatch.fnmatchcase(part, pat):
                return False
        return True
409021
def read_match_config_from_file(match_config_path: Path) -> MatchConfig:
    
    config_obj = create_bot_config_layout()
    config_obj.parse_file(match_config_path, max_index=MAX_PLAYERS)
    return parse_match_config(config_obj, match_config_path, {}, {})
969609
def _parse_title(file_path):
    
    title = file_path
    title = title.split('/')[-1]
    title = '.'.join(title.split('.')[:-1])
    title = ' '.join(title.split('-'))
    title = ' '.join([
        word.capitalize()
        for word in title.split(' ')
    ])
    return title
376832
def match(self, filepath):
        
        # no extension?
        if filepath.find(".") == -1:
            return False

        # match extension
        return filepath.lower().split(".")[-1] in self.__extensions
782961
def do_grep(self, path, match):
        
        try:
            children = self.get_children(path)
        except (NoNodeError, NoAuthError):
            children = []

        for child in children:
            full_path = os.path.join(path, child)
            try:
                value, _ = self.get(full_path)
            except (NoNodeError, NoAuthError):
                value = ""

            if value is not None:
                matches = [line for line in value.split("\n") if match.search(line)]
                if len(matches) > 0:
                    yield (full_path, matches)

            for mpath, matches in self.do_grep(full_path, match):
                yield (mpath, matches)
75371
def match(self, path: str) -> Tuple[Optional[Dict[str, Any]], bool]:
        
        match = self._pattern.match(path)
        if match is not None:
            # If the route is a branch (not leaf) and the path is
            # missing a trailing slash then it needs one to be
            # considered a match in the strict slashes mode.
            needs_slash = (
                self.strict_slashes and not self.is_leaf and match.groupdict()['__slash__'] != '/'
            )
            try:
                converted_varaibles = {
                    name: self._converters[name].to_python(value)
                    for name, value in match.groupdict().items()
                    if name != '__slash__'
                }
            except ValidationError:  # Doesn't meet conversion rules, no match
                return None, False
            else:
                return {**self.defaults, **converted_varaibles}, needs_slash
        else:
            return None, False
1330630
def segment_text(text=os.path.join(DATA_PATH, 'goodreads-omniscient-books.txt'),
                 start=None, stop=r'^Rate\ this', ignore=r'^[\d]'):
    
    start = start if hasattr(start, 'match') else re.compile(start) if start else None
    stop = stop if hasattr(stop, 'match') else re.compile(stop) if stop else None
    ignore = ignore if hasattr(ignore, 'match') else re.compile(ignore) if ignore else None

    segments = []
    segment = []
    with open(text) as fin:
        for line in fin:
            if start is not None and start.match(line):
                segments += [segment] if len(segment) else []
                segment = [line]
            elif stop is not None and stop.match(line):
                segments += [segment]
                segment = []
            elif ignore is not None and ignore.match(line):
                continue
            else:
                segment += [segment]
1281808
def find_matches(text):
    
    """
    path = os.path.expanduser(text)
    if os.path.isdir(path) and not path.endswith('/'):
        return [ text + '/' ]

    pattern = path + '*'
    is_implicit_cwd = not (path.startswith('/') or path.startswith('./'))
    if is_implicit_cwd:
        pattern = './' + pattern
    rawlist = glob.glob(pattern)
    ret = []
    for fname in rawlist:
        if is_implicit_cwd:
            fname = fname[2:]
        if os.path.isdir(fname):
            ret.append(fname + '/')
        else:
            ret.append(fname)
    return ret
459952
public Object match(String path)
    {
        Map.Entry entry = getMatch(path);
        if (entry!=null)
            return entry.getValue();
        return null;
    }
638486
def reader(path):
    
    p = subprocess.Popen(
        ['7z', 'e', '-so', path],
        stdout=subprocess.PIPE,
        stderr=file_open(os.devnull, "w")
    )
    return io.TextIOWrapper(p.stdout, encoding='utf-8',
                            errors='replace')
780530
def _search_files(path):
        
        path = pathlib.Path(path)
        fifo = []

        for fp in path.glob("*"):
            if fp.is_dir():
                continue
            for fmt in formats:
                # series data is not supported in SeriesFolder
                if not fmt.is_series and fmt.verify(fp):
                    fifo.append((fp, fmt.__name__))
                    break

        # ignore qpimage formats if multiple formats were
        # detected.
        theformats = [ff[1] for ff in fifo]
        formset = set(theformats)
        if len(formset) > 1:
            fmts_qpimage = ["SingleHdf5Qpimage", "SeriesHdf5Qpimage"]
            fifo = [ff for ff in fifo if ff[1] not in fmts_qpimage]
        # ignore raw tif files if single_tif_phasics is detected
        if len(formset) > 1 and "SingleTifPhasics" in theformats:
            fmts_badtif = "SingleTifHolo"
            fifo = [ff for ff in fifo if ff[1] not in fmts_badtif]
        # otherwise, prevent multiple file formats
        theformats2 = [ff[1] for ff in fifo]
        formset2 = set(theformats2)
        if len(formset2) > 1:
            msg = "Qpformat does not support multiple different file " \
                  + "formats within one directory: {}".format(formset2)
            raise MultipleFormatsNotSupportedError(msg)
        # sort the lists
        fifo = sorted(fifo)
        return fifo
692181
def parse_content(self, content):
        
        # note, the Parser class sets:
        # * self.file_path = context.path and
        # * self.file_name = os.path.basename(context.path)
        self.active_lines_unparsed = get_active_lines(content) if content is not None else []
        #  (man page shows all options with "=")
        self.active_settings = split_kv_pairs(content, use_partition=False) if content is not None else []
1138165
def parse_file(file_or_path, encoding='utf-8', validate=False):
    
    try:
        is_string = isinstance(file_or_path, basestring)
    except NameError:
        is_string = isinstance(file_or_path, str)
    if is_string:
        with codecs.open(file_or_path, 'r', encoding) as file_:
            result = pattern.parseFile(file_)[0]
    else:
        result = pattern.parseFile(file_or_path)[0]
    if validate:
        result.validate()
    return result
262055
def get_words(file_path=None, content=None, extension=None):
    
    if (file_path is None and (content is None or extension is None) or
                    file_path and content and extension):
        error_msg = ('Must provide `file_path` or `content` and `extension`')
        raise Exception(error_msg)

    if file_path and content is None and extension is None:
        extension = os.path.splitext(file_path)[1]
        with open(file_path) as infile:
            content = infile.read()

    if extension in ['.css']:
        regex = re.compile(r'([^a-zA-Z-])')
    elif extension in ['.R', '.c', '.md', '.cpp', '.java', '.py']:
        regex = re.compile(r'([^a-zA-Z_])')
    else:
        regex = re.compile(r'([^a-zA-Z])')

    words = sorted(set(regex.sub(r' ', content).split()))
    return words
987230
def match(path, search)
      matches = get_matches(path)

      if matches.length > 0
        match = matches.sort { |m| m[1] }.first

        @params = match[2]
        add_search_to_params(search)

        match[0]
      else
        nil
      end
    end