Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9064485
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T16:15:52+00:00 2026-06-16T16:15:52+00:00

I want to let the user choose and open multiple texts and perform a

  • 0

I want to let the user choose and open multiple texts and perform a search for exact matches in the texts.
I want the encoding to be unicode.

If I search for “cat” I want it to find “cat”, “cat,”, “.cat” but not “catalogue”.

I don’t know how to let the user search for two words (“cat” OR “dog”) in all of the texts at the same time??????
Maybe I can use RE?

So far I have just made it possible for the user to insert the path to the directory containing the text files to search in. Now I want to let the user (raw_input) search for two words in all of the texts, and then print and save the results (e.g. “search_word_1” and “search_word_2” found in document1.txt, “search_word_2” found in document4.txt) in a separate document (search_words).

import re, os


path = raw_input("insert path to directory :")
ex_library = os.listdir(path)
search_words = open("sword.txt", "w") # File or maybe list to put in the results
thelist = []

for texts in ex_library:
    f = os.path.join(path, texts)
    text = open(f, "r")
    textname = os.path.basename(texts)
    print textname
    for line in text.read():

    text.close()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T16:15:54+00:00Added an answer on June 16, 2026 at 4:15 pm

    Regular expressions are appropriate tool in this case.

    I want it to find “cat”, “cat,”, “.cat” but not “catalogue”.

    Pattern: r'\bcat\b'

    \b matches at a word boundary.

    how to let the user search for two words (“cat” OR “dog”) in all of the texts at the same time

    Pattern: r'\bcat\b|\bdog\b'

    To print "filename: <words that are found in it>":

    #!/usr/bin/env python
    import os
    import re
    import sys
    
    def fgrep(words, filenames, encoding='utf-8', case_insensitive=False):
        findwords = re.compile("|".join(r"\b%s\b" % re.escape(w) for w in words),
                               flags=re.I if case_insensitive else 0).findall
        for name in filenames:
            with open(name, 'rb') as file:
                 text = file.read().decode(encoding)
                 found_words = set(findwords(text))
                 yield name, found_words
    
    def main():
        words = [w.decode(sys.stdin.encoding) for w in sys.argv[1].split(",")]
        filenames = sys.argv[2:] # the rest is filenames
        for filename, found_words in fgrep(words, filenames):
            print "%s: %s" % (os.path.basename(filename), ",".join(found_words))
    
    main()
    

    Example:

    $ python findwords.py 'cat,dog' /path/to/*.txt
    

    Alternative solutions

    To avoid reading the whole file in memory:

    import codecs
    
    ...
    with codecs.open(name, encoding=encoding) as file:
        found_words = set(w for line in file for w in findwords(line))
    

    You could also print found words in the context they are found e.g., print lines with highlighted words:

    from colorama import init  # pip install colorama
    init(strip=not sys.stdout.isatty())  # strip colors if stdout is redirected
    from termcolor import colored  # pip install termcolor
    
    highlight = lambda s: colored(s, on_color='on_red', attrs=['bold', 'reverse'])
    
    ...
    regex = re.compile("|".join(r"\b%s\b" % re.escape(w) for w in words),
                       flags=re.I if case_insensitive else 0)
    
    for line in file:
        if regex.search(line): # line contains words
           line = regex.sub(lambda m: highlight(m.group()), line)
           yield line
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want let the user choose what style my application has.Small example would be
I'm using a UIActionSheet to let the user choose one of multiple actions. One
I want to let user to choose a directory for saving a file. but
I'm implementing yet another battery widget :) I want to let user choose widget
This is what I want : Let the user enter as many numbers as
I have a Multiline Textbox . I donot want to let user type HTML
So I have a file for constants. I want to let user define them
I want to let the user download the current content of a textarea into
I'm using jquery ui draggable, I do not want to let the user drag
Selenium provide many kinds of browser driver, so I want to let the user

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.