Check of two words are present in text file or not. Python script

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Davetherave
    New Member
    • Nov 2018
    • 1

    Check of two words are present in text file or not. Python script

    The two words should be present or none should be present in text file. User should input two words and that word should be check into the text file be it any type such as .html,.txt,.doc ,.php using python.
  • Luuk
    Recognized Expert Top Contributor
    • Mar 2012
    • 1043

    #2
    One of the answers give in the internet seems to be correct, so I will try to show hoe you can test this yourself.

    Create some textfile (I will name it 'example.txt'), with the following content:
    Code:
    bla
    bla
    ble
    blu
    blo
    bla
    The example says to do this to find 1 occurrence of your search text:
    Code:
    if 'bla' in open('example.txt').read():
        print("true")
    This seems to work:
    Code:
    C:\temp>python
    ActivePython 3.5.3.3505 (ActiveState Software Inc.) based on
    Python 3.5.3 (default, May 16 2017, 01:12:46) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> if "bla" in open("example.txt").read():
    ...   print("true")
    ...
    true
    >>> if "blx" in open("example.txt").read():
    ...   print("true")
    ...
    >>>
    Let's first create a script with this example. Store the following in a text-file ame 'search.py'
    Code:
    if "bla" in open("example.txt").read():
       print("true")
    and run: python search.py

    you should get the result saying: true

    Now, how to find if that word exists two (or more) times in example.txt?

    Google for "find number of occurrences in a text in a string"
    and change search.py to:
    Code:
    if "bla" in open("example.txt").read():
       print("true")
    
    a = open("example.txt").read()
    print(a.count("bla"))
    When typing: python search.py
    The answer should be:
    Code:
    true
    3
    (providing you followed above instructions ;)

    This should help you on your way to find the complete solution to your question.
    Last edited by Luuk; Dec 1 '18, 02:50 PM. Reason: some formatting changed...

    Comment

    Working...